Auto-property initializers in C#

Automatic properties is good feature in C# as we don’t have to declare variables for property values in our code. Instead we move this responsibility to compiler that automatically generated hidden backing field for property. New C# solves another problem – assigning default values to automatic properties.

Suppose we have the following automatic property defined in our class:

class MyClass

{

    public string Dummy { get; set; }

}

This far we have assigned default values to automatic properties in constructor like here:

class MyClass

{

    public string Dummy { get; set; }

 

    public MyClass()

    {

        Dummy = “Hello!”;

    }

}

In new C# we can do it shorter way:

class MyClass

{

    public string Dummy { get; set; } = “Hello!”;

}

Yes, we just write default value after property definition.

Some things to know:

  1. Behind the scenes the value is assigned directly to backing field and therefore setter is not called.
  2. You can’t use “this” with default values because default values are assigned in some point of time during class initialization and it’s possible that not all members are initialized for this moment.

Anyway I like this short syntax for automatic properties as it helps to keep class constructors cleaner is some cases.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    2 thoughts on “Auto-property initializers in C#

    • November 11, 2014 at 10:07 pm
      Permalink

      You said “You can’t use “this” with default values because default values are assigned in some point of time during class initialization and it’s possible that not all members are initialized for this moment.”

      Can you give a code sample of this? I don’t understand.

    • November 12, 2014 at 12:37 pm
      Permalink

      Yes, sure. You can’t do something like this:

      public string Property1 { get; set; } = “ABC”;
      public string Property2 { get; set; } = Property1;

    Leave a Reply

    Your email address will not be published. Required fields are marked *