Srikrishna Sallam
Srikrishna Sallam

Reputation: 764

Set properties of a class only through constructor

I am trying to make the properties of class which can only be set through the constructor of the same class.

Upvotes: 40

Views: 42167

Answers (4)

Dhanuka777
Dhanuka777

Reputation: 8636

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/

Upvotes: 14

Marc Ziss
Marc Ziss

Reputation: 709

As of c# 6.0 you now can have get only properties that can be set in the constructor (even though there is no set defined in the property itself. See Property with private setter versus get-only-property

Upvotes: 10

stephenbayer
stephenbayer

Reputation: 12431

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; }
}

Upvotes: 65

David Morton
David Morton

Reputation: 16505

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; } }
}

Upvotes: 21

Related Questions