Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

TIP: Initialization of auto-implemented properties in structs

, 4 Sep 2010
Rate this:
Please Sign up or sign in to vote.
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.

License

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

Share

About the Author

Jaime Olivares
Architect Freelance (jaimeolivares.com)
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 C# 2013 and TFS.
Can be reached at http://www.jaimeolivares.com
Follow on   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinmemberVJ Reddy13-Apr-12 16:24 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 4 Sep 2010
Article Copyright 2010 by Jaime Olivares
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid