C# Reference ยท Keywords and Statements
The readonly keyword
Reference for C# readonly: read-only fields, readonly structs and readonly members, shallow immutability, defensive copies and how it differs from const.
readonly marks a value that can be set only once. On a field, it means the field may be assigned in its declaration or inside a constructor of the same type, and nowhere else. After the object is built, the field never changes. Unlike const, a readonly field is initialized at run time, so it can hold any value: a list, a DateTime, an object created with new.
The keyword has three other uses. A readonly struct promises that every field of the struct is read-only. A readonly member of a struct promises that the member does not modify the struct. And ref readonly returns or passes a reference that the receiver cannot write through.
class Account { public readonly string Id; public Account(string id) => Id = id; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
[modifiers] readonly Type name [= initializer]; // field readonly struct Name { ... } // type readonly record struct Name(...); // type struct S { public readonly int M() { ... } } // member ref readonly T Get(); // return / local void F(ref readonly T value); // parameter (C# 12)
| Form | Meaning |
|---|---|
readonly field |
Assignable only in the declaration, in an instance constructor (instance fields) or in the static constructor (static fields). An init accessor of the same type may also assign it. |
readonly struct |
All instance fields must be read-only and all properties get-only or init-only. The compiler can skip defensive copies. |
readonly member |
The member may not change the struct's fields. Allowed on methods, properties and accessors of a non-readonly struct. |
ref readonly |
A reference that can be read but not assigned through. |
Errors: assigning a readonly field outside a constructor gives CS0191; assigning a field of a readonly struct gives CS8340; calling a mutating method through a readonly reference compiles but works on a copy (see below).
Usage notes
- Shallow only.
readonlyfreezes the variable, not the object it refers to. Areadonly List<string>field can still have items added. For real immutability use an immutable type such asImmutableArray<T>or exposeIReadOnlyList<T>. - Where assignment is allowed. An instance readonly field can be assigned in its initializer or in any instance constructor of its class, including one reached through
this(...). Static readonly fields are assigned in a static initializer or the static constructor. - Versus
const. Aconstis a compile-time constant copied into every caller that uses it; astatic readonlyfield is read at run time. Changing aconstin a library requires recompiling the callers, changing astatic readonlydoes not. Useconstfor values that truly never change (numbers, strings),static readonlyfor the rest. - Readonly structs avoid copies. When you call a method on a readonly struct held in a
readonlyfield or aninparameter, the compiler knows the call cannot change it. On an ordinary mutable struct it must copy the value first, because the method might modify it. Mark small value typesreadonly structunless you truly need mutation. - A common trap. A mutable struct stored in a readonly field is copied before each method call, so a mutating method seems to do nothing. Another reason to keep structs immutable.
- readonly members (C# 8) let you mark individual methods and properties of a mutable struct as non-mutating. The compiler checks it and removes the defensive copy.
- Records.
record structcan be declaredreadonly record struct, giving init-only properties. Arecord classis not affected byreadonly; its positional properties are already init-only. - Reflection can still change readonly fields. Treat
readonlyas a compile-time guarantee for well-behaved code.
Related
- const
- init
- struct
- ref, out and in
- Tutorial: Constants and readonly, Structs