C# 3.0 Auto-Implemented Properties

This is a minor but useful enhancement in my opinion in that auto-implemented properties solve a couple of problems.

The first is the age old pain that has been around since at least the C++ get and set method days, where a property is merely a thin layer hiding your data, you used to have to write all the standard plumbing code yourself.  Now you don’t have to.

C# 2.0 Example

public string ExampleText
{
get { return _exampleText; }
set { _exampleText = value; }
}private string _exampleText;

C# 3.0 Equivalent

public string ExampleText
{
get;
set;
}

You can see in the C# 2.0 example that you have to write the body of the get and set properties yourself, in C# 3.0 you merely declare the property in the same way that you would in an interface.

The compiler will then create a private anonymous variable of the correct type and tie it to the property for you.  This variable can only be accessed via the property but if your design evolves and you need to provide your own implementation later then you can do so.

You must specify BOTH the get and set accessors in order to have the compiler auto-implement the properties for you.

Access Modifiers

The second problem that has been solved is one of access.  Due to get and set properties being manually implemented as separate methods in unmanaged C++, it was possible and usual to specify a public get method and a private/protected set method.  This has now been implemented for properties in C#.

public string ExampleText
{
get;
private set;
}

The above example shows that it is possible to override the access modifier on either a get or a set method.  The property must however adhere to the following rules:

  1. If you are going to set the access level on the get or set declaration, the level specified must be different to that specified on the property iteself.
  2. You cannot specify access modifiers for BOTH accessors (both get and set).
  3. The access modifier on an accessor must be MORE restrictive than the property as a whole.

Each of the rules above are broken in the examples below:

string SameAccessibility { get; private set; } // private is the default
public string TooManyAccessors { internal get; private set; }
private string LessRestrictive{get; public set;}
string OnlyOne{get;} // Error caused by only one accessor being specified.

To read about more C# 3.0 enhancements click here.

Tags:

Leave a Reply

You must be logged in to post a comment.