Auto-Implemented Properties

.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.

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Related posts

Comments

July 23. 2007 01:39 PM

trackback

Trackback from DotNetKicks.com

Auto-Implemented Properties

DotNetKicks.com

August 18. 2008 01:32 PM

sonal rattan

I think you'll find this example is incorrect, the first example returns String.empty asthe variable has been initialised - where as the auto property will return a null!!

sonal rattan

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

November 20. 2008 02:57 PM