In C#, how do const and static readonly fields differ, and why does a changed public const in a shared library not reach compiled callers?
answer
- compile time versus run time
- the value travels into the caller
- built-in types and string only
- readonly guards the field, not the object
- case labels need a constant
basics
~20 sA const is a compile-time value copied into every caller's IL, so callers keep the old value until they are recompiled. A static readonly field is read from its assembly at run time, may have any type and is assigned once.
solid answer
~50 s`const` declares a compile-time constant: the initializer must be a constant expression, the type must be a built-in numeric type, `bool`, `char`, `string` or an enum (other reference types only `null`), and the compiler substitutes the value at every use. Because the value lives in the caller's IL, a payroll app built against `TaxRules.BasicRateThreshold = 50_270m` keeps 50270 after only the library DLL is redeployed with a new value. `static readonly` is a field assigned in its initializer or static constructor (CS0198 anywhere else); callers load it at run time, so a library-only update is seen, and it can hold any type, such as a `Dictionary`. `readonly` fixes only the field reference, not the dictionary's contents. Use `const` for values that never change, or where C# demands a constant: `case` labels, attribute arguments, default parameter values.
code
csharp · 14 linesusing System;
using System.Collections.Generic;
Console.WriteLine(TaxRules.BasicRateThreshold);
Console.WriteLine(TaxRules.Bands["basic"]);
TaxRules.Bands["basic"] = 25;
Console.WriteLine(TaxRules.Bands["basic"]);
static class TaxRules
{
public const decimal BasicRateThreshold = 50_270m;
public static readonly decimal HigherRateThreshold = 125_140m;
public static readonly Dictionary<string, int> Bands = new() { ["basic"] = 20, ["higher"] = 40 };
}go deeper
Recall that const is a compile-time value limited to built-in types, string and enums, while static readonly is a run-time field that holds any type and is assigned once.
Explain that the compiler copies a const value into each caller's IL, which is why case labels and attributes accept it, and why readonly protects a field reference but not its object.
Diagnose a library hotfix that callers do not see: find the public const, explain why only a recompile fixes it, and move changeable values to static readonly.
Set the rule for shared libraries: public const only for truly fixed values, static readonly or properties for anything a release can change, and read-only types for lookup tables.
## Two kinds of "never changes" C# has two ways to declare a value that code cannot reassign, and they are fixed at different times: | | `const` | `static readonly` | |---|---|---| | When the value is fixed | compile time | run time, once, when the type initializes | | Allowed types | built-in numeric types, `bool`, `char`, `string`, enums; other reference types only `null` | any type | | Where it is assigned | only in its declaration, from a constant expression | in the field initializer or the static constructor | | `static` modifier | implicit; writing `static const` is CS0504 | written explicitly | | How another assembly reads it | the value is copied into the caller's IL | the caller loads the field at run time | | Usable in `case` labels, attribute arguments, default parameter values | yes | no | ## What the compiler does with a `const` A `const` is a **compile-time constant**. Wherever code names it, the compiler substitutes the value itself; there is no field load at run time. That is why a `const` can appear in a `case` label, an attribute argument or an optional parameter's default value, and why a `static readonly` field cannot: the .NET 10 SDK reports **CS9135** ("A constant value of type 'int' is expected") for a `case` label, **CS0182** for an attribute argument and **CS1736** for a default parameter value. `decimal` is a special case worth knowing. The CLR has no `decimal` literal, so the compiler emits a `public const decimal` as a static `initonly` field marked with `DecimalConstantAttribute`. Callers' compilers read that attribute and still copy the value in, so a `const decimal` versions exactly like any other `const`. ## The shared-library trap Picture a payroll solution whose shared library declares: ```csharp public static class TaxRules { public const decimal BasicRateThreshold = 50_270m; public static readonly decimal HigherRateThreshold = 125_140m; } ``` 1. The import app is built against this library and prints both values: 50270 and 125140. 2. A hotfix changes both thresholds, and only the library DLL is rebuilt and copied next to the app. 3. The app now prints 50270 and the new higher threshold: the `static readonly` value moved, the `const` did not. The app's IL holds the value 50270 itself and never asks the library for it. Only recompiling the app against the new library picks up the change. The C# documentation warns about exactly this: do not make a `const` of information you expect to change over time, such as a price, a product version number or a brand name. ## Which types can be `const` - Built-in numeric types (including `decimal`), `bool`, `char`, `string` and enum types. - Other reference types only with `null`: `public const int[] Weeks = { 52, 53 };` is **CS0133** ("The expression being assigned to 'Rules.Weeks' must be constant"). - Structs such as `DateTime` cannot be `const` at all: **CS0283** ("The type 'DateTime' cannot be declared const"). - Since **C# 10**, an interpolated string can be `const` when every placeholder is itself a constant string: `$"rules-{Version}"` compiles when `Version` is a `const string`, while `$"rules-{Threshold}"` with a `decimal` placeholder is CS0133. ## What `static readonly` does and does not protect A `static readonly` field may be assigned only in its initializer or the static constructor; anywhere else the SDK reports **CS0198** ("A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)"). That protects the **field**, not the object it refers to. A lookup table declared as `public static readonly Dictionary<string, int> Bands` can still have entries added, removed or overwritten by any caller. If the contents must stay fixed, expose a read-only or frozen collection type, which the material on immutable and frozen collections covers. ## Choosing in a code review - Use `const` for values that are true forever, such as `MonthsPerYear = 12`, and for `private` or `internal` constants used only by code that is compiled together. - Use `static readonly` for anything a later release may change (tax thresholds, rates, URLs, version strings) and for any type that cannot be `const`. - Keep a mutable lookup table behind a read-only type even when its field is `static readonly`.
- Reflection shows a `public const decimal` as a static `initonly` field, not a literal; is it still copied into callers?Yes. The CLR has no `decimal` literal, so the compiler emits the constant as an `initonly` static field marked with `DecimalConstantAttribute`. A calling assembly's compiler reads that attribute and emits the value directly, so the caller never loads the field. Redeploying only the library leaves the caller on the old value, exactly as with an `int` constant.
- When is a `public const` safe to expose from a shared library?When the value can never change, such as the number of months in a year, or when every consumer is always rebuilt together with the library. Anything a later release might change, such as thresholds, rates, version strings or URLs, should be `static readonly` or a property, so a library-only update reaches callers. `private` and `internal` constants raise no such issue for code compiled together.
- Why does `case TaxRules.Months:` fail when `Months` is a `static readonly int`?A `case` label needs a constant the compiler can evaluate, and a `static readonly` field only gets its value at run time. The .NET 10 SDK reports CS9135 ("A constant value of type 'int' is expected"). Attribute arguments (CS0182) and default parameter values (CS1736) have the same requirement, so those places need a `const`.
A const is a price printed on a product's label at the factory: changing the price list later does not reprint labels already on the shelf. A static readonly field is the price the till looks up when the item is scanned, so a new price list takes effect at once.
- Redeploying the library DLL updates every caller's const value
- static readonly makes the Dictionary it holds read-only
- A const field must also be marked static
- Any struct, such as DateTime, can be declared const
- static readonly values are computed at compile time like const
- A static readonly field can be reassigned from any static method