Understanding the 'readonly' Keyword in C#

C# readonly Keyword

The readonly keyword is used to define a read-only field or variable. Once a field is marked as readonly, its value can only be assigned during object initialization or within the constructor of the class. After that, the value cannot be changed, ensuring that the field remains constant throughout the lifetime of the object.

Usage of the readonly keyword:

public class ExampleClass
{
    public readonly int ReadOnlyField;

    // Constructor to initialize the readonly field.
    public ExampleClass(int value)
    {
        ReadOnlyField = value;
    }

    // Other members and methods of the class go here.
}

In this example, ReadOnlyField is a read-only field of type int. It is initialized in the constructor, and once the object is created, its value cannot be changed.

Key points to note about readonly:

  1. Read-only fields can be either instance-level fields (without the static keyword) or static fields (with the static keyword). In both cases, the value can only be set during declaration or within the class constructor.

  2. The readonly keyword can only be used with fields, not with properties or local variables.

  3. Read-only fields must be assigned a value either directly when declared or within the constructor of the class. After that, the value cannot be modified.

Here's an example of using a read-only field:

public class Circle
{
    public readonly double Pi;
    public double Radius;

    public Circle(double radius)
    {
        Pi = 3.14159; // Initializing the readonly field.
        Radius = radius;
    }

    public double CalculateArea()
    {
        return Pi * Radius * Radius;
    }
}

// Usage example:
Circle circle = new Circle(5.0);
double area = circle.CalculateArea();

In this example, the Pi field is marked as readonly and is set to the value of π (pi) during the object's construction. Since Pi is read-only, its value remains constant throughout the life of the Circle object.

Using the readonly keyword is beneficial when you have fields that should not be changed after initialization, providing additional safety and clarity to your code. It can be particularly useful when dealing with constant values or values that are set during object creation and remain the same throughout the object's lifetime.