Page 187 - CSharp/C#
P. 187
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,
6.0
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
https://riptutorial.com/ 133

