Property Initializers in C-Sharp 6.0

In the C-Sharp 3.0 a new feature Automatic property got introduced. It allows us to create a class as a bag of the 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 filed. When you set value of the property, setter gets executed to set the value of the backing field. Now catch is that to create a read only property you have to invoke the setter in the constructor of the class and make set as private

public class Product
    {
        public int Price { get; private set; }
        public string Name  { get; set; }

        public Product()
        {
            Price  = 10;
        }

    }

In the above class definition the Price property is read only and set to the default value 10 and you can 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-sharp 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 value if the backing field.

image

As you see in the above snippet we are setting the default value of Price property as 10. However after creating the instance of the class. Value of price property can be changed. If you wish you can create read only property by removing the setter.

image

Since setter is optional, it is easier to create immutable properties. For your reference 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 post discussing purpose of the auto property initializer. It allows us to create immutable property with the user defined default value. Now to create properties with default values, you don’t have to invoke setter.

Happy coding.

One response to “Property Initializers in C-Sharp 6.0”

  1. It’s very cool, very useful

Leave a comment

Create a website or blog at WordPress.com