1.6 — const vs readonly vs init vs required¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.5 static · Next: 1.7 Inheritance
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
constis decided when you compile, and the value gets copied into every project that uses it. That copying is the trap.readonlyis decided when the program runs. You set it in the declaration or in the constructor, then it is locked.initlets you set a property only while creating the object.requiredforces the caller to set it at all.
The concept¶
All four of these mean some version of "you cannot change this". The difference is when the value gets locked in:
| Keyword | Locked in at |
|---|---|
const |
Compile time — before the program ever runs |
readonly |
End of the constructor |
init |
End of object creation |
required |
(Does not lock anything — it forces the caller to provide a value) |
The const copying issue is the real reason this question gets asked. It causes a bug
that is genuinely baffling if you have not seen it before.
How it works¶
const — frozen at compile time¶
The value must be something the compiler can work out on its own. It is automatically
static. You can only use it for simple built-in types: numbers, bool, char, string,
and null.
public const int MaxRetries = 3;
public const string ApiVersion = "v1";
public const DateTime Epoch = new DateTime(1970, 1, 1);
// ERROR. Creating a DateTime requires running code,
// and the compiler cannot run code. Use static readonly instead.
Now the trap. When you use a const from another project, the compiler does not look
it up at runtime. It copies the actual value into your compiled code.
Here is what that means in practice:
- Your library
PaymentLibhaspublic const int MaxRetries = 3; - Your app references
PaymentLiband usesMaxRetries. - The compiler writes the literal number
3into your app's compiled file. - You ship a new
PaymentLibwhereMaxRetries = 5. - You drop the new DLL in without recompiling the app.
- Your app still uses 3. The new value is completely ignored.
This is very hard to debug, because you can open the library, see 5, and watch the app
behave as if it were 3.
The rule: use const only for values that will never change — mathematical
constants, fixed protocol numbers, things you would be happy carving into stone. For
anything else that is public, use static readonly. It looks exactly the same to whoever
is using it, but it is read at runtime, so an updated library takes effect immediately.
readonly — frozen after the constructor¶
You can assign it in two places: where you declare it, or inside a constructor. Nowhere else. It is evaluated while the program runs, so any expression is allowed.
public class Service
{
private readonly IRepository _repo; // set in constructor
private static readonly DateTime Started = DateTime.UtcNow; // set at first use
public Service(IRepository repo) => _repo = repo;
}
The second trap: readonly protects the variable, not the object it points to.
private readonly List<string> _items = new();
_items = new List<string>();
// ERROR — you cannot point the field at a different list.
_items.Add("this is completely allowed");
// FINE — the list itself is still a normal, changeable list.
Going back to the analogy from 1.1: readonly means
you cannot rub out the address written on the paper. It does nothing to stop anyone
walking into the house and rearranging the furniture.
For real protection you need a type that genuinely cannot change. Expose it as
IReadOnlyList<T> so callers cannot see Add, or use ImmutableArray<T> if you want it
enforced properly.
init — set it while creating the object, then never again¶
Introduced in C# 9. An init property can be assigned in an object initialiser (the
{ ... } block when you use new) or in a constructor, and after that it is locked.
public class Person
{
public string Name { get; init; }
}
var p = new Person { Name = "Ada" }; // Allowed — we are still creating it
p.Name = "Grace"; // ERROR — creation is finished
Before init existed, you had to choose between two bad options: a constructor with a long
list of parameters, or a class where everything stays changeable forever. init gives you
the readable { Name = ... } syntax and immutability.
required — the caller must supply it¶
Introduced in C# 11. This one is different from the other three: it does not control whether something can change, it controls whether the caller is allowed to leave it out.
public class Person
{
public required string Name { get; init; } // must be given, then locked
public string? Nickname { get; init; } // optional
}
var a = new Person { Name = "Ada" }; // Fine
var b = new Person(); // COMPILE ERROR: you did not set Name
Notice that last line fails at compile time, not at runtime. That is the whole value: "you forgot to set Name" changes from a null reference exception in production into a red squiggle in your editor.
required plus init together give you the safety of a constructor with the readability
of an object initialiser.
Code¶
public class OrderProcessor
{
// This genuinely never changes. const is fine.
private const int MaxLineItems = 100;
// This might change in a future version, and it is public.
// static readonly, so consumers pick up the new value without recompiling.
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30);
// Injected once at construction and never replaced.
private readonly IPaymentGateway _gateway;
public OrderProcessor(IPaymentGateway gateway) => _gateway = gateway;
}
public record CreateOrderRequest
{
// Caller MUST provide these. Compile error if they forget.
public required Guid CustomerId { get; init; }
public required IReadOnlyList<OrderLine> Lines { get; init; }
// Genuinely optional
public string? PromoCode { get; init; }
}
Interview questions¶
Q: What is the difference between const and readonly?
const is worked out at compile time, is automatically static, and only works for simple
built-in types like numbers and strings. readonly is worked out at runtime and can be
assigned either where it is declared or inside a constructor, so it can hold any type and
any computed value. The important practical difference is that const values get copied
into every project that uses them. So if you change a public const in a library, every
application using it keeps the old value until it is recompiled. That makes
static readonly much safer for anything public that might ever change.
Q: Does readonly make an object immutable?
No. It makes the field unassignable — you cannot point it at a different object. If the
field holds something changeable like a List, you can still add and remove items freely.
For genuine immutability the type itself has to be immutable, so you would expose it as
IReadOnlyList<T> or use something like ImmutableArray<T>.
Q: What does init give you that a constructor does not?
Object initialiser syntax. Before init, making a class immutable meant writing a
constructor, and a class with ten mostly-optional properties meant either a huge parameter
list or a builder class. With init you can set properties by name, in any order, leaving
out the ones you do not need — and the property is still locked afterwards. Add required
and the compiler also checks you did not forget the mandatory ones, so you get the safety
of a constructor with the readability of an initialiser.
Q: When would you use required?
For any property the object cannot be valid without, when you do not want to write a constructor. It is especially good for DTOs and configuration classes that have a mix of mandatory and optional properties. The benefit is that forgetting one becomes a compile error instead of a null reference exception somewhere later.
Traps ⚠️¶
- Changing a public
constin a library is a breaking change that does not look like one. Consumers keep the old value until they recompile. Usestatic readonlyfor public values that could ever change. readonlyon a field holding an object does not freeze the object. Only the field.constcannot hold aDateTime,TimeSpan, or anything built withnew. Those needstatic readonly.readonlycan still be changed by reflection. It is a compile-time promise, not a runtime lock.requiredis not validation. It is checked when your code creates the object. A JSON deserializer or an ORM that builds objects a different way can still leave it unset. For real input validation use proper validation attributes — see 11.4.
Related¶
- 1.2 Records — where
initappears automatically - 1.5 static —
static readonlyfields - 1.15 Nullability —
requiredand non-nullable properties together - 7.7 Binding configuration to classes — using
initandrequiredin options classes