What is the difference between const and readonly in C#?
Quick Answer
const is a compile-time constant — its value is baked into the calling code at compile time, must be set at declaration, and is implicitly static. readonly is a run-time constant — set at declaration or in the constructor, can differ per instance, and can hold any type including objects.
const is resolved at compile time — the value gets literally copied into wherever it's used — so it has to be a primitive or string set right at the declaration, and it's always static. readonly is a runtime value: I can set it in the constructor, it can be a different value per instance, and it can be any type. The subtle gotcha with const is versioning across assemblies — if a referenced library changes a public const, my code keeps the old value until I recompile. So for public library constants I use static readonly instead.
| const | readonly | |
|---|---|---|
| Set when | Declaration only | Declaration or constructor |
| Evaluated | Compile time | Run time |
| Types allowed | Primitives, string, enum, null | Any type |
| static | Always (implicitly) | Optional |
| Per-instance value | No | Yes |
The versioning trap: if library A exposes public const int Max = 10 and app B compiles against it, the literal 10 is copied into B. Ship A v2 with Max = 20 and B still uses 10 until recompiled. A public static readonly int Max is read from A at run time, so B picks up the new value. Use const only for values that are truly fixed forever (Math.PI-style); use static readonly for public library values.