Property Initializers in C# 6.0

In C# 3.0 a new feature Automatic property was introduced. It allows us to create a class as a bag of the setters and the getters. You can create a class as follows:

  1. public class Product  
  2. {  
  3.     public int Price { getset; }  
  4.     public string Name  { getset; }  
  5.   

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.

  1. public class Product  
  2. {  
  3.     public int Price { getprivate set; }  
  4.     public string Name  { getset; }  
  5.   
  6.     public Product()  
  7.     {  
  8.         Price  = 10;  
  9.     }  
  10.   

In the preceding class definition the Price property is read only and 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 default value without invoking the setter. This feature of C# 6.0 is called Property Initializers.

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 the Property Initializer is given below:

  1. using System;  
  2. namespace demo1  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Product p = new Product  
  9.             {  
  10.                   
  11.                 Name = "Pen"  
  12.   
  13.             };  
  14.   
  15.             Console.WriteLine(p.Price);  
  16.   
  17.             Console.ReadKey(true);  
  18.         }  
  19.     }  
  20.   
  21.     public class Product  
  22.     {  
  23.         public int Price { get;} = 10;   
  24.         public string Name  { getset; }  
  25.     }  

We can summarize this article with the purpose of the auto property initializer. It allows us to create an immutable property with the user defined default value. Now to create properties with default values, you don't need to invoke the setter.

Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all