Click here to Skip to main content
15,879,348 members
Articles / Programming Languages / C#
Tip/Trick

TIP: Initialization of auto-implemented properties in structs

Rate me:
Please Sign up or sign in to vote.
4.83/5 (20 votes)
4 Sep 2010CPOL 19.2K   4   1
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:

C#
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:

C#
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:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Peru Peru


Computer Electronics professional, Software Architect and senior Windows C++ and C# developer with experience in many other programming languages, platforms and application areas including communications, simulation systems, PACS/DICOM (radiology), GIS, 3D graphics and HTML5-based web applications.
Currently intensively working with Visual Studio and TFS.

Comments and Discussions

 
GeneralMy vote of 5 Pin
VJ Reddy13-Apr-12 16:24
VJ Reddy13-Apr-12 16:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.