In C# 6.0, a new feature has been added to set the default values of the public properties, called Auto-property initializers. Using the auto-property initializers, we can set default values to the properties without having to use a constructor. Let us consider a simple example of the Author class as shown in the listing below:
As you notice in the above listing, the default value of the Articles property is set to 10. So while creating the object, if the value of the Articles property is not set then it would be set to the default value 10. In the below listing, we are not setting the value of the Articles property of the object a, hence it is set to the default value of 10.
Author a = new Author { Name = "Chandan" };
The auto-property initializer sets the value of the property directly into the backing field without invoking the setters. Prior to C# 6.0, we used to create read only properties by creating a private setter and then setting the value in the constructor. However in C#6.0, using the auto-property initializer, a read only property can be easily created as shown in the listing below:
Creating a read only property with a default value is now super easy using the Auto-property initializer, making it one of my favorite feature of C# 6.0.
0 comments :
Post a Comment