Blog

Filter posts by Category Or Tag of the Blog section!

init only property in C#

Monday, 14 December 2020

C# 9 came with some cool features. One of them was the init keyword. Simply, you can initialize a property or the indexer element only during the construction. Take a look at the following property definition:

public class Product
{
    public string Name { get; init; }
    public string SerialNumber { get; init; }
}

You can only init the above properties like below:

  public Product()
    {
        this.Name = "Mobile"; // OK
        this.SerialNumber = "237498263"; // Ok
    }

Or even in a method:

public void InitializeViaMethod()
    {
        var  myPerson = new Product
        {
            Name = "Laptop", // works
            SerialNumber = "w34523244" // works
        };
    }

But you are not allowed to initialize like below:

public void InitializeViaMethod()
    {
        var  myPerson = new Product
        {
            Name = "Laptop", // works
            SerialNumber = "w34523244" // works
        };
 
        myPerson.Name = "change the first name"; // Error (CS8852)
        myPerson.SerialNumber = "change the last name"; // Error (CS8852)
    }

 

Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.

 

Now, what’s the difference between init-only and readonly properties?

The main difference is that you can not initialize a property with readonly modifier in the constructor but the init-only property has been introduced just for this purpose!

Category: Software

Tags: C#

comments powered by Disqus