Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 182 ยท Variables and Types

Constants and readonly

Learn the difference between const, readonly and static readonly in C# - compile-time constants, constant expressions, versioning traps and when to use each.

Some values should never change while your program runs: the number of days in a week, the tax rate of a calculation, the maximum length of a user name. If such a value lives in an ordinary variable, any line of code can modify it by accident. C# gives you two tools to say "this does not change": const, for values known when the code is compiled, and readonly, for values that are set once while the program runs. Combined with static they cover every case, and picking the right one avoids a subtle bug that has bitten many libraries.

This lesson explains what each keyword does, how they differ at compile time and at run time, what a constant expression is, and a simple rule for choosing.

const: compile-time constants

A const is declared with a value that the compiler can compute. After that, assigning to it is a compile error.

C# A const cannot change

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.

Trying to modify it is rejected by the compiler:

C# Assigning to a const (fails on purpose)

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.

The message is error CS0131: The left-hand side of an assignment must be a variable, property or indexer. A constant is a named value, not a variable, so there is no place to store a new value in.

Constants follow the naming convention for their kind of member: local constants are often camelCase or PascalCase (teams differ); public const fields are PascalCase, such as MaxPlayers. Do not use SCREAMING_CASE, which is a convention from other languages.

What counts as a constant expression

The value of a const must be a constant expression: something the compiler can fully evaluate. That includes literals, other constants, and operators applied to them. It also includes interpolated strings whose placeholders are all constant strings (C# 10); a number inside the braces would not qualify.

C# Constant expressions

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.

Only a small set of types may be const: the numeric types, bool, char, string, enums, and null for reference types. You cannot make a List<int>, a DateTime, or your own class instance a const, because the compiler cannot build such objects while compiling. The next two keywords exist for those cases. Another limitation: const values are always static; writing static const is an error.

What the compiler does with a const

This is the most important and least-known fact about const: the compiler copies the value into every place where you use the constant. The name disappears from the compiled code; only the literal remains. That makes const as fast as writing the number yourself, and it enables things like switch case labels and default parameter values that only accept compile-time values:

C#
const int Admin = 1;
switch (role)
{
    case Admin:           // case labels must be constants
        break;
}

But the copying has a side effect when the constant lives in a library used by another project. If you change the value in the library and rebuild only the library, the other project still contains the old value until you recompile it too. That is why a published public const must be something that truly never changes (like Math.PI or the number of months in a year), not "the current maximum upload size".

readonly: set once at run time

A readonly field can be assigned only in its declaration or in a constructor. After that it is fixed. The value may be calculated while the program runs, and the field can be of any type.

C# readonly instance fields

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.

Each Order can have a different Id, which is impossible for a const. The attempt to assign first.Id outside the constructor would report error CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer).

Look carefully at Lines. The variable is read-only, meaning it always points at the same list. The list is an ordinary object, so adding items works. readonly freezes the reference, not the object behind it. If you need a collection that cannot change, see Immutable, Frozen and Read-only Collections.

static readonly: one shared run-time constant

Add static and the field belongs to the type instead of each object. It is set once, when the type is first used, by a static initializer or a static constructor. This is the right choice for a shared value that is not a compile-time constant.

C# static readonly for shared values

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.

DateTime, HashSet<string>, TimeSpan and a tuple cannot be const, but all work with static readonly. The value is computed one time at run time, and reading it afterwards is as cheap as reading any static field.

const versus static readonly

const static readonly
When is the value set? At compile time Once at run time, when the type is initialized
Allowed types Primitives, string, enums, null Any type
Allowed in case labels, attribute arguments, default parameters Yes No
Copied into other assemblies Yes, so they must be recompiled No, they read the current value
Implicitly static Yes You write static

The practical rule:

  1. If the value will never change in the life of the product and is a primitive, string or enum, use const.
  2. If it might change between versions, or it is not a primitive, use static readonly.
  3. If every object needs its own value fixed at construction, use an instance readonly field.

Other ways to say "does not change"

C# has more tools for immutability, which later lessons cover in depth:

  • Local const: shown above, handy to name a "magic number" inside one method.
  • Read-only properties: public int Id { get; } can only be set in the constructor, much like a readonly field but with a property's flexibility. See Properties.
  • init properties and records make whole objects immutable: Records.
  • readonly struct and in parameters keep structs from changing: Structs.
  • Enums give names to a fixed set of integer constants: Enums and Flags.

Naming a number is worth doing even when it is used once. if (age >= 18) makes a reader ask "why 18?", while if (age >= LegalAge) explains itself and gives one place to change it.

C# Magic numbers replaced by names

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.

Changing the tax rate or the free-shipping limit now means editing a single line, and the arithmetic lines read like the business rules they implement. (The m suffix makes decimal literals, explained in the lesson about floating-point numbers and decimal.)

A const of a reference type other than string can only be null. If you ever think "I need a const list", you want static readonly (and probably an immutable collection type).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which declaration is valid?

    const needs a compile-time value of a primitive, string or enum type. DateTime.UtcNow and new List are run-time values, and const is already implicitly static.
  2. 2. When can a readonly instance field be assigned?

    readonly fields are assigned in the declaration (initializer) or inside a constructor of the same class. Afterwards the compiler rejects assignments.
  3. 3. What does readonly guarantee for a field of type List<string>?

    readonly freezes the reference, not the object. Items can still be added unless the object itself is immutable.
  4. 4. Why is a public const in a library risky if the value may change?

    The compiler inlines constants. A dependent project built against the old library keeps the old value; static readonly is read at run time and avoids this.
  5. 5. Which is the best choice for a shared TimeSpan timeout value of 30 seconds?

    TimeSpan is not allowed for const, and the value is shared by the whole program, so static readonly fits.

Summary

  • const creates a compile-time constant from a constant expression; allowed types are primitives, string, enums and null. It is implicitly static and is inlined wherever it is used.
  • readonly fields are set in their declaration or a constructor and can hold any run-time value, but only the reference is frozen, not the object.
  • static readonly is a shared, run-time constant of any type and the default choice when const is not allowed.
  • A changed public const is not seen by already compiled code in other assemblies, so publish only values that never change as const.
  • Replace magic numbers with named constants so rules read clearly and live in one place.

Next: Value Types and Reference Types