Introduction
On November 12, 2014, the day of the Visual Studio Connect() event, Microsoft announced Visual Studio 2015 Preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is Auto Property Initializer.
Don't forget to read my previous posts on this series: "A new feature of C# 6.0"
What is an Auto Property Initializer.?
The Auto Property feature was first added to the C# language with the release of C# 3.0 on 19 November 2007 as a part of .NET Framework 3.5 that allows us to define the property without any backing field, however we still need to use constructors to initialize these auto properties to a non-default value. With the release of C# 6.0, a new feature called Auto Property Initializer allows us to initialize these properties without a constructor. In C# 6.0, we can now initialize the properties where they are declared.
Example 1
The following code snippet defines a class Student with one auto property, Name, and a parameterized constructor has been defined to initialize this property to some value.
Note that
- Both the declaration and assignment are in different places.
- We can't have a "get" only auto-property.
In C# 6.0, the same code can be rewritten as shown below.
What is Getter Only Auto-Properties?
Properties can be made read-only by removing the setter accessor. That can be done by having only a get accessor in the property implementation. With no setter, immutability is easier to do.
Example 2
The following code only has a getter accessor.
Example 3
To make the set accessor available only to code within the class, we can use the private access modifier. The property will appear to be read-only when accessed from outside of the defined (where the property is defined with a private set accessor) class.
- When the declaration and assignment of the get accessor and set accessor are in a single class, we can easily initialize the values using the setter accessor in that class.
- When the declaration and assignment of the get accessor and set accessor are in a different class we are unable to initialize the values using a setter accessor in another class except where they are declared.
![Setter inaccessible]()
Demo Application using Visual Studio 2013.
Output
![Property]()
Demo Application using Visual Studio 2015 Preview.
Output
![VS15 output]()
Summary
In this article, we learned how to initialize the Auto Property Initializer without using a constructor and can be initialized where they are declared. I hope you liked this feature of C# 6.0. Don't forget to read my other articles on the series " A new feature of C# 6.0". Share your opinion about this feature and how will you use it in your project. Your comments are most welcome. Happy Coding!