Sobes.tech
Junior — Middle

Is it possible to make a field read-only in a class so that its value cannot be changed after initialization?

sobes.tech AI

Answer from AI

In C#, you can create a read-only field using the readonly modifier. Such a field can be initialized either at the declaration or in the class constructor, after which its value cannot be changed.

Example:

class MyClass
{
    public readonly int MyReadOnlyField;

    public MyClass(int value)
    {
        MyReadOnlyField = value; // initialization in constructor
    }
}

You can also use a property with only a getter and a private setter or no setter at all, and initialize it through the constructor or at declaration (starting from C# 6.0):

class MyClass
{
    public int MyProperty { get; }

    public MyClass(int value)
    {
        MyProperty = value;
    }
}

After initialization, the value of such a property cannot be changed.