ZetCode

C# readonly

last modified November 6, 2026

In this article we show how to use the readonly keyword in C#. The readonly modifier on a field means that the field can be assigned only in its declaration or in a constructor of the same class. After the object is constructed, the field cannot be changed.

The readonly keyword helps us express immutability and prevents accidental modifications. Besides fields, it can be applied to structs, struct members, and parameters passed by reference.

C# readonly field

The following example uses readonly fields.

Program.cs
var c1 = new Circle(2.5);
c1.Print();

var c2 = new Circle(4);
c2.Print();

class Circle
{
    private readonly double _radius;
    private readonly string _unit = "cm";

    public Circle(double radius)
    {
        _radius = radius;

        if (radius > 3)
        {
            _unit = "m";
        }
    }

    public void Print()
    {
        Console.WriteLine($"Radius: {_radius} {_unit}, area: {Math.PI * _radius * _radius:F2}");
    }
}

The Circle class has two readonly fields.

private readonly double _radius;
private readonly string _unit = "cm";

The _unit field has an initializer, the _radius field does not.

public Circle(double radius)
{
    _radius = radius;

    if (radius > 3)
    {
        _unit = "m";
    }
}

Inside the constructor, the fields can be assigned, even several times. The constructor may overwrite the value of the initializer. Any assignment in an ordinary method, or from outside the class, is a compile error:

error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer)

The Print method only reads the fields.

$ dotnet run
Radius: 2.5 cm, area: 19.63
Radius: 4 m, area: 50.27

The readonly vs const keywords

A const field is a compile-time constant. Its value must be known when the program is compiled, and only numbers, booleans, characters, strings, enums, and null are allowed. A readonly field is assigned at run time, and it can be of any type.

Program.cs
Console.WriteLine($"Const value: {Config.MaxUsers}");
Console.WriteLine($"Static readonly value: {Config.StartedAt:yyyy}");

var c = new Config("production");
Console.WriteLine($"Readonly value: {c.Environment}");

Console.WriteLine(Config.Default.Environment);

class Config(string environment)
{
    public const int MaxUsers = 100;

    public static readonly DateTime StartedAt = DateTime.Now;

    public static readonly Config Default = new("development");

    public readonly string Environment = environment;
}

The Config class has a constant, two static readonly fields, and an instance readonly field.

public const int MaxUsers = 100;

A constant is implicitly static. The compiler copies its value into every place where it is used, even in other assemblies. If the value changes, the dependent assemblies must be recompiled; therefore, constants are suitable only for values that never change.

public static readonly DateTime StartedAt = DateTime.Now;

public static readonly Config Default = new("development");

A DateTime or an object instance cannot be a constant. A static readonly field is initialized once, when the type is initialized.

public readonly string Environment = environment;

An instance readonly field may have a different value for each object. Here it is initialized from a parameter of the primary constructor.

$ dotnet run
Const value: 100
Static readonly value: 2026
Readonly value: production
development

readonly with reference types

For a field of a reference type, readonly means that the field always refers to the same object. The object itself can still be modified.

Program.cs
var team = new Team("Alice");
team.Show();

team.Rename("Bob");
team.Show();

team.AddMember("Carol");
team.AddMember("Dave");
Console.WriteLine(string.Join(", ", team.Members));

class Person
{
    public required string Name { get; set; }
}

class Team(string leader)
{
    private readonly Person _leader = new() { Name = leader };
    private readonly List<string> _members = [];

    public IReadOnlyList<string> Members => _members;

    public void Show() => Console.WriteLine($"Leader: {_leader.Name}");

    public void Rename(string name) => _leader.Name = name;

    public void AddMember(string name) => _members.Add(name);
}

The Team class has two readonly fields of reference types.

public void Rename(string name) => _leader.Name = name;

We cannot assign a new Person to the _leader field, but we can change the properties of the existing person.

private readonly List<string> _members = [];

public IReadOnlyList<string> Members => _members;

Similarly, a readonly list field can be modified with Add. To prevent callers from modifying the list, we expose it through the IReadOnlyList<T> interface.

$ dotnet run
Leader: Alice
Leader: Bob
Carol, Dave

Read-only and immutable collections

.NET has read-only views of collections, immutable collections, and frozen collections. They differ in what can change.

Program.cs
using System.Collections.Frozen;
using System.Collections.Immutable;

List<string> source = ["red", "green", "blue"];

IReadOnlyList<string> view = source.AsReadOnly();
source.Add("yellow");
Console.WriteLine(string.Join(", ", view));

ImmutableArray<string> colors = [.. source];
ImmutableArray<string> more = colors.Add("black");

Console.WriteLine(string.Join(", ", colors));
Console.WriteLine(string.Join(", ", more));

FrozenSet<string> allowed = source.ToFrozenSet();
Console.WriteLine(allowed.Contains("green"));

try
{
    ((ICollection<string>) view).Add("white");
}
catch (NotSupportedException e)
{
    Console.WriteLine(e.Message);
}

We create several kinds of collections from a list.

IReadOnlyList<string> view = source.AsReadOnly();
source.Add("yellow");

The AsReadOnly method returns a ReadOnlyCollection wrapper. It cannot be modified through the wrapper, but it reflects changes of the underlying list.

ImmutableArray<string> colors = [.. source];
ImmutableArray<string> more = colors.Add("black");

An immutable collection never changes. Methods such as Add return a new collection and leave the original intact.

FrozenSet<string> allowed = source.ToFrozenSet();

Frozen collections, available since .NET 8, are immutable collections optimized for fast lookups. They are created once and read many times.

((ICollection<string>) view).Add("white");

When we cast the read-only view to a mutable interface and call Add, we get a NotSupportedException.

$ dotnet run
red, green, blue, yellow
red, green, blue, yellow
red, green, blue, yellow, black
True
Collection is read-only.

C# readonly struct

A readonly struct is an immutable value type. All its fields must be readonly and all its auto-implemented properties must be get-only or init-only. The compiler enforces this:

error CS8341: Auto-implemented instance properties in readonly structs must be readonly.

The following example defines a readonly struct and a readonly record struct.

Program.cs
var p1 = new Point(3, 4);
Console.WriteLine(p1);
Console.WriteLine(p1.Length);

var p2 = p1.WithX(10);
Console.WriteLine(p2);

var c = new Coord(1, 2);
var c2 = c with { Y = 5 };
Console.WriteLine(c2);

readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;

    public double Length => Math.Sqrt(X * X + Y * Y);

    public Point WithX(double x) => new(x, Y);

    public override string ToString() => $"({X}, {Y})";
}

readonly record struct Coord(int X, int Y);

The Point struct cannot be modified after creation.

public Point WithX(double x) => new(x, Y);

Instead of modifying the point, the WithX method returns a new one.

readonly record struct Coord(int X, int Y);

A readonly record struct generates read-only properties from its parameters, along with equality members and ToString. The with expression creates a modified copy.

$ dotnet run
(3, 4)
5
(10, 4)
Coord { X = 1, Y = 5 }

C# readonly members

When a struct is mutable as a whole, we can still mark individual methods and properties as readonly. A readonly member promises not to modify the state of the struct.

Program.cs
var counter = new Counter();

counter.Increment();
counter.Increment();

Console.WriteLine(counter.Describe());
Console.WriteLine(counter.Value);

struct Counter
{
    public int Value { get; private set; }

    public void Increment() => Value++;

    public readonly string Describe() => $"Counter at {Value}";
}

The Counter struct has a mutating method and a readonly method.

public readonly string Describe() => $"Counter at {Value}";

The Describe method is marked as readonly. The compiler reports an error if it tries to change the struct. It also helps performance: the compiler does not need to make defensive copies when the method is called on a readonly instance.

$ dotnet run
Counter at 2
2

C# in and ref readonly parameters

Structs are passed by value, which means they are copied. For large structs, the copy can be expensive. The in and ref readonly modifiers pass a struct by reference, while forbidding the method to modify it.

Program.cs
var m = new Matrix4(1.5);

Console.WriteLine(Sum(in m));
Console.WriteLine(MaxDiagonal(in m));

static double Sum(in Matrix4 matrix)
{
    return matrix.M11 + matrix.M22 + matrix.M33 + matrix.M44;
}

static double MaxDiagonal(ref readonly Matrix4 matrix)
{
    return Math.Max(Math.Max(matrix.M11, matrix.M22), Math.Max(matrix.M33, matrix.M44));
}

readonly struct Matrix4(double v)
{
    public readonly double M11 = v, M12 = 0, M13 = 0, M14 = 0;
    public readonly double M21 = 0, M22 = v, M23 = 0, M24 = 0;
    public readonly double M31 = 0, M32 = 0, M33 = v, M34 = 0;
    public readonly double M41 = 0, M42 = 0, M43 = 0, M44 = v;
}

The Matrix4 struct contains sixteen doubles; it takes 128 bytes.

static double Sum(in Matrix4 matrix)

The in parameter passes the matrix by reference. Assigning to matrix inside the method is a compile error.

static double MaxDiagonal(ref readonly Matrix4 matrix)

The ref readonly parameter, available since C# 12, is similar. It signals that the argument should be a variable rather than a temporary value; the compiler warns if it is passed without in or ref.

$ dotnet run
6
1.5

Source

readonly keyword - language reference

In this article we have shown how to use the readonly keyword in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.