Introduction

Properties can be initialized with the = operator after the closing \\}. The Coordinate class below shows the available options for initializing a property:

public class Coordinate
{ 
    public int X { get; set; } = 34; // get or set auto-property with initializer
		public int Y { get; } = 89;      // read-only auto-property with initializer              
}

Accessors With Different Visibility

You can initialize auto-properties that have different visibility on their accessors. Here’s an example with a protected setter:

public string Name { get; protected set; } = "Cheeze";

The accessor can also be internal, internal protected, or private.

Read-Only Properties

In addition to flexibility with visibility, you can also initialize read-only auto-properties. Here’s an example:

public List<string> Ingredients { get; } = 
        new List<string> { "dough", "sauce", "cheese" };

This example also shows how to initialize a property with a complex type. Also, auto-properties can’t be write-only, so that also precludes write-only initialization.

Old style (pre C# 6.0)

Before C# 6, this required much more verbose code. We were using one extra variable called backing property for the property to give default value or to initialize the public property like below,

public class Coordinate
{
    private int _x = 34;
    public int X { get { return _x; } set { _x = value; } }

    private readonly int _y = 89;
    public int Y { get { return _y; } }
    
    private readonly int _z;
    public int Z { get { return _z; } }

    public Coordinate()
    {
        _z = 42;
    }
}

Note: Before C# 6.0, you could still initialize read and write auto implemented properties (properties with a getter and a setter) from within the constructor, but you could not initialize the property inline with its declaration

View Demo

Usage

Initializers must evaluate to static expressions, just like field initializers. If you need to reference non-static members, you can either initialize properties in constructors like before, or use expression-bodied properties. Non-static expressions, like the one below (commented out), will generate a compiler error:

// public decimal X { get; set; } = InitMe();  // generates compiler error

decimal InitMe() { return 4m; }