X

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.

Liked this post? Empower your friends by sharing it!
Categories: C#

View Comments (2)

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

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

    public string Property1 { get; set; } = "ABC";
    public string Property2 { get; set; } = Property1;

Related Post