- Posted by Ian Suttle on July 20, 2007
- Filed under .NET 3.5
.Net Framework's Auto-Implemented Properties, also known as Automatic Properties, are a nifty way of saving a few lines of code without sacrificing performance. Previous to .Net 3.5 one would typically write a property as follows (C#):
string _name = string.Empty;
public string Name
{
get { return _name; }
set { _name = value; }
}
Let's pretend creating the local variables to hold our simple property value is mundane (okay, it is). Wouldn't it be oh so nice to cut this down to the following code:
public string Name { get; set; }
public string Country { get; private set; } //creates a read-only property
Well you're in luck because that's all there is to it! When this code is compiled, the compiler will output equivalent logic to the pre-.Net 3.5 property. Naturally this isn't practicle if you want to modify the private/protected value vs. the public value, but for the basic property such as one you may find in an entity class, Auto-Implemented Properties are quite useful.