Coming soon to C#: Auto-property initializers

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.

NB! You can try new language features out on Visual Studio 14 CTP. It’s free to download!

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.


2 thoughts on “Coming soon to C#: Auto-property initializers

  • 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.

  • Gunnar says:

    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 *