Wednesday, 7 December 2016

40 C# Auto properties

Automatic properties

A real pain in the neck for all programmers writing object oriented code has always been declaring public properties for all the private fields. This is a lot of tedious work, especially because almost all properties will be a simple get and set mapping to the private field, without anything clever added, like this:
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.

No comments:

Post a Comment