Automatically Implemented Properties

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 might look something like the code below.

private int myProperty = 0;
public int MyProperty
{
   get { return this.myProperty; }
   set { this.myProperty = value; }
}

A simpler example that uses automatically implemented properties for the same field is below.

public int MyProperty
{
   get; set;
}

However, it is important not to be too lazy and use this haphazardly. Examine the code below where you define a Customer class. Take note of the CustomerKey property that is defined. Typically, such a key field is a readonly item that is set once and doesn’t change. When taking a shortcut using automatically implemented properties, it allows for undesired behavior with the code.

class Customer
{
   public string CustomerKey { get; set; }
   public string ContactName { get; set; }
   public string City { get; set; }
}

You might try refactoring the code to have a private set and use a constructor to control the value. Although this does protect the field from the outside, it could still be altered internally to the class.

class Customer
{
   public Customer(string customerKey)
   {
      CustomerKey = customerKey;
   }

   public string CustomerKey { get; private set; }
   public string ContactName { get; set; }
   public string City { get; set; }
}

In reality, an automatically implemented property probably isn’t appropriate for the CustomerKey property and the code should look like the example below. The class in question in this example is pretty simple, but it illustrates the point that the automatically implemented properties should be applied liberally, but with caution.

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; }
}

Related Research:

Related Articles:

Visit us for more Programming and Technology Research.

  • Digg
  • Faves
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati
  • LinkedIn
  • Twitter
  • DZone
  • Tumblr

Speak Your Mind

*