Set properties of a class only through constructor

With C# 9 it introduces 'init' keyword which is a variation of 'set', which is the best way to do this.

The one big limitation today is that the properties have to be mutable for object initializers to work: They function by first calling the object’s constructor (the default, parameterless one in this case) and then assigning to the property setters.

Init-only properties fix that! They introduce an init accessor that is a variant of the set accessor which can only be called during object initialization:

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

Ref: https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/


This page from Microsoft describes how to achieve setting a property only from the constructor.

You can make an immutable property in two ways. You can declare the set accessor.to be private. The property is only settable within the type, but it is immutable to consumers. You can instead declare only the get accessor, which makes the property immutable everywhere except in the type’s constructor.

In C# 6.0 included with Visual Studio 2015, there has been a change that allows setting of get only properties from the constructor. And only from the constructor.

The code could therefore be simplified to just a get only property:

public class Thing
{
   public Thing(string value)
   {
      Value = value;
   }

   public string Value { get; }
}

Make the properties have readonly backing fields:

public class Thing
{
   private readonly string _value;

   public Thing(string value)
   {
      _value = value;
   }

   public string Value { get { return _value; } }
}