DevCity.NET - http://devcity.net
Auto-implemented Class Properties
http://devcity.net/Articles/358/1/article.aspx
Roger McCook
Roger is an independent programmer in Atlanta, Georgia and president of McCook Software, Inc. (www.McCookSoftware.com). He focuses on Microsoft technologies including VB, C#, ASP.NET, and SQL Server. For the past eight years he has spent most of his time developing advanced systems for the telecom giant BellSouth (now a part of AT&T). Roger is a published author of many technical articles as well as fictional short stories. You can email him at: RogerMcCook@bellsouth.net 
by Roger McCook
Published on 9/6/2008
 
Auto-implemented properties is not a difficult subject, only a simple concept that can make your programs easier to code and read.

Auto-implemented Class Properties

This article is a brief overview of auto-implemented class properties, a concept first included with version 3.0 of the .NET platform released in June, 2006. This won't work with previous versions.*

The term "auto-implemented properties" may sound exotic. You may be tempted to put off learning it. You may think it is complex and will take a long time to absorb. No, this is a simple topic you can learn in a few minutes. It will save time and make your code easier to read.

Let's take a simple Employee Class. This is how we used to code a single property within the class:

 private string _LastName;
  
 public string LastName
 {
         get { return _LastName; }
         set { _LastName = value; 
  }

We initialised a private variable for the employee last name. Then we created a public property. The public property consists of the get and set accessors. The get accessor returns the value in the private variable. The set accessor sets the private variable equal to the value implicitly passed to the property.

With auto-implemented properties, we can reduce the above code to a single line: 

 public string LastName { get; set; }

We do not need to define a private variable. When we assign a value to the property within the class (in a constructor or other function), we just use the property name (LastName = "Jones"). Behind the scenes, the compiler creates the private, anonymous variable that is automatically used by the property accessors.

We can add a modifer to limit the scope. For example, to make the property read-only by the consumer of the class:

 public string LastName { get; private set; }

Here are a couple of additional tips:

  • If you need to implement some logical constraints within the property to adhere to some business rule, don't use the new auto-implemented format. This is strictly for those properties that we are using like a public variable while still respecting the concept of encapsulation. 
  • Auto-implemented properties must use both the get and set accessors. 

 


*  [Editor's Note]   At the time of writing, this feature is only available in C#.