In C# 3.0 a new feature, the Automatic property, was introduced. It allows us to create a class as a bag of setters and the getters. You can create a class as follows:
- public class Product
- {
- public int Price { get; set; }
- public string Name { get; set; }
-
- }
Each property is backed by a backing field. When you set the value of the property, the setter is executed to set the value of the backing field. Now the catch is that to create a read only property you need to invoke the setter in the constructor of the class and make the set private.
- public class Product
- {
- public int Price { get; private set; }
- public string Name { get; set; }
-
- public Product()
- {
- Price = 10;
- }
-
- }
In the preceding class definition the Price property is read only and is set to the default value 10 and you cannot set the value of the name property outside the class.
To create a read only property with the default value, we created a private setter and then set the default value in the constructor. In C# 6.0, you can directly create a read only property with a default value without invoking the setter. This feature of C# 6.0 is called
Property Initializers.A Property Initializer allows you to create a property with the default value without invoking the setter. It directly sets the value of the backing field.
As you see in the preceding snippet we are setting the default value of the Price property to 10. However after creating the instance of the class the Value of the price property can be changed. If you wish you can create a read only property by removing the setter.
Since the setter is optional, it is easier to create immutable properties. For your reference the source code harnessing Property Initializer is given below:
- using System;
- namespace demo1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Product p = new Product
- {
-
- Name = "Pen"
-
- };
-
- Console.WriteLine(p.Price);
-
- Console.ReadKey(true);
- }
- }
-
- public class Product
- {
- public int Price { get;} = 10;
- public string Name { get; set; }
- }
- }
We can summarize this article discussing the purpose of the auto property initializer. It allows us to create the immutable property with a user defined default value. Now to create properties with default values, you don't need to invoke the setter.
Happy coding.