65.9K
CodeProject is changing. Read more.
Home

TIP: Initialization of auto-implemented properties in structs

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (20 votes)

Jun 14, 2010

CPOL
viewsIcon

19607

How to initialize auto-implemented properties in structure constructors

C# 3.0 has a great feature called auto-implemented properties. The main benefit is readability: we don't need to declare an underlying field for each property, as:
public struct Place
{
     public string City { get; set; }  // auto-implemented property
     public string State { get; set; } 
     public string Country { get; set; }
}
But, when we try to initialize some of these properties in a structure's custom constructor, we get a compiler error like: The 'this' object cannot be used before all of its fields are assigned to, like in the following snippet:
public struct Place  // custom constructor
{
     public string City { get; set; }
     public string State { get; set; }
     public string Country { get; set; }

     Place(string city, string state, string country)
     {
         this.City = city; this.State = state; this.Country = country;
     }
}
The reason is that C# rules enforce to initialize all fields in the constructor before using them. The problem is that underlying fields of properties are hidden! Fortunately the solution is simple: call the default constructor from the custom constructor, like:
Place(string city, string state, string country) : this() // invoking default constructor
{
    this.City = city; this.State = state; this.Country = country;
}
The default constructor will initialize all hidden fields to their default values. After this, they can be used in the custom constructor through their corresponding properties.