I am trying to make the properties of class which can only be set through the constructor of the same class.
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.
Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.
Constructors are special methods in C# that are automatically called when an object of a class is created to initialize all the class data members. If there are no explicitly defined constructors in the class, the compiler creates a default constructor automatically.
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With