readonly

suggest change

The readonly keyword is a field modifier. When a field declaration includes a readonly modifier, assignments to that field can only occur as part of the declaration or in a constructor in the same class.

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used.

The readonly keyword is often used when injecting dependencies.

class Person
{
    readonly string _name;
    readonly string _surname = "Surname";

    Person(string name)
    {
        _name = name;
    }
    void ChangeName()
    {
        _name = "another name"; // Compile error
        _surname = "another surname"; // Compile error
    }
}

Note: Declaring a field readonly does not imply immutability. If the field is a reference type then the content of the object can be changed. Readonly is typically used to prevent the reference from being overwritten after the object is instantiated.

Note: Inside the constructor, a readonly field can be reassigned

public class Car
{
    public double Speed {get; set;}
}

//In code

private readonly Car car = new Car();

private void SomeMethod()
{
    car.Speed = 100;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents