C# 3.0 Automatic Properties

  • 4 minutes to read
  • edit

Defining properties can be very tedious. Suppose you have a class

public class UserProfile
{
    private int userrId;
    private string firstName;
    private string lastName;

    public int UserId
    {
        get { return this.userId; }
        set { this.userId = value; }
    }

    public string FirstName
    {
        get { return this.firstName; }
        set { this.firstName = value; }
    }
    
    public string LastName
    {
        get { return this.lastName; }
        set { this.lastName = value; }
    }

    public UserProfile() { }   
}

It might not look like a lot of code, but when you think about the steps you need to go through to write that small amount of code, it can add up.

  1. Decide on the public property name.
  2. Declare the appropriately named and typed backing variable.
  3. Implement the corresponding public property.

Fortunately, C# 3.0 provides a way to simplify this. Now, we can write the class this way:

public class UserProfile
{
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public UserProfile() { }
}

This is certainly much more compact and requires fewer steps. When the compiler sees this class, (according to Reflector) it translates it to:

public class UserProfile
{
    [CompilerGenerated]
    private int <UserId>k_BackingField;
    [CompilerGenerated]
    private string <FirstName>k_BackingField;
    [CompilerGenerated]
    private string <LastName>k_BackingField;
    
    public int UserId
    {
        [CompilerGenerated]
        get
        {
            return this.<UserId>k_BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.<UserId>k_BackingField = value;
        }
    }

    public string FirstName
    {
        [CompilerGenerated]
        get
        {
            return this.<FirstName>k_BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.<FirstName>k_BackingField = value;
        }
    }
            
    public int LastName
    {
        [CompilerGenerated]
        get
        {
            return this.<LastName>k_BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.<LastName>k_BackingField = value;
        }
    }

    public UserProfile() { }           
}

There are a few things to look out for when using this syntax. The compiler forces you to declare properties with both a get and a set. You also don’t get any kind of “safety” features, such as ensuring that you don’t allow a null value to be assigned to a string property. If you want these more “advanced” features, you’ll still need to define your property the “old school” way.

Comments