Automatically Implemented Properties (C#)

C# 3.0 was released as a part of the Microsoft .NET 3.5 Framework. In this blog post, I’ll cover the automatically implemented properties feature of C# 3.0. Automatically implemented properties offer a concise syntax for implementing property accessors that get and set a private field. They create a field backed property without requiring you to actually create a field. The compiler automatically generates it for you at compile time. They can be used only for simple get and set of properties because there is no body and no field. No property body means no breakpoints or validation logic can be used. No field means no default value. Typing "prop [tab][tab]" is the Visual Studio code snippet for producing an automatically implemented property. This can make your code much more concise. A classic example of a field back property is shown below:
 
private int myProperty = 0;
 
public int MyProperty
{
   get { return this.myProperty; }
   set { this.myProperty = value; }
}
 
The above code snippet can be refactored to use automatically implemented properties as shown below:
 
public int MyProperty
{
   get; set;
}
 
The above code snippet can be refactored to include a private set and use a constructor to control the value as shown below:
 
class Customer
{
   public Customer(string customerKey)
   {
      CustomerKey = customerKey;
   }
 
   public string CustomerKey { get; private set; }
   public string ContactName { get; set; }
   public string City { get; set; }
}
 
Although this does protect the field from the outside, it could still be altered internally to the class. In reality, an automatically implemented property probably isn’t appropriate for the CustomerKey property and the above code snippet can be further refactored to:
 
class Customer
{
   public Customer(string customerKey)
   {
      this.CustomerKey = customerKey;
   }
   private readonly string customerKey;
 
   public string CustomerKey
   {
      get return this.customerKey;
   }
 
   public string ContactName { get; set; }
   public string City { get; set; }
}
 
The above code snippet illustrates the point that the automatically implemented properties should be applied liberally, but with caution.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: