Automatic properties
private string name; public string Name { get { return name; } set { name = value; } }With a simple property like that, we could pretty much just as well have declared the field as public and used it directly, instead of adding the extra layer of a property. However, the guidelines of OOP tells us to do it this way, and most of us resists the temptation of doing it the easy way. With C# 3.0 we don't have to deal with this dilemma anymore! The above example can now be written like this instead:
public string Name { get; set; }Or using even less space, like this:
public string Name { get; set; }No field declaration, and no code to get and set the value of the field. All of that is handled automatically by the compiler, which will automatically create a private field and populate the get and set method with the basic code required to read and write the field. From the outside, this will look just like a regular property, but you saved a lot of extra keystrokes and your class will be less bloated. Of course, you can still use the old way, as shown in our first example - this is simply an extra feature that you can use, if you feel like it.
Having problems with this chapter? Ask in our forums!
Could this article help your friends? Please help us to help them by sharing it on Facebook or Twitter: