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


Bookmark and Share

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

March 11. 2009 10:12 AM

Perfect Home Design

im sure its automated on its properties

Perfect Home Design

April 20. 2009 12:41 AM

Auto Franchise

Hey - just checking out the blogengine.net platform on yoru site as I am looking to change over from wordpress. How are you finding it's backend and themes?

Cheers

Matthew Anderson

Auto Franchise

April 25. 2009 05:57 AM

Raymond Kirk

Good post, but have you thought about Auto-Implemented Properties before?

Raymond Kirk

Comments are closed