, , , ,

C# 3.0 and later versions give developers the ability to have underlying property structures automatically taken care by the compiler, which behind the scenes, creates the private members and implements the get and set inner workings. In this posting, I’ll cover how to create regular and automated properties in C#.

Before automated properties became available, the only way to create properties was to write code for each property we wanted to make available through our class. The snapshot below displays a Person class being consumed by the Program class. The Person class has three properties: FirstName, LastName, and DateOfBirth. In order to implement these properties in the correct encapsulated way, we needed three private members (declared at the top) that will only be accessible through the public properties.


Now, let’s see what changes when using automated properties. After modifying the Person class above to use automated properties, we have the following code:


The differences are clear. We basically replaced a regular block property declaration with a single line declaration by adding {get; set; } to the member declaration. The compiler will automatically create basic get and set blocks and the result will be transparent to other classes consuming your class. In addition to make it easier to create properties, we have also saved about 18 lines of code by switching just three properties to auto mode. Imagine not having to type several lines of code for classes requiring lots of properties.

You can also make one or more of your properties immutable by declaring the set accessor private. For instance, in our Person class, a Person might get married and need to change the Last Name, but the Date of Birth will never change. The code below displays how we can make DateOfBirth immutable using automated properties:

Immutable Property Implementation

As we can see from the snapshot above, we just needed to declare the set accessor as private during the member declaration to prevent users from changing property values once the object has been created. The downside of this approach is that a constructor needs to be implemented in order to populate the immutable property at the time the class is instantiated.

Have Fun!