Difference between “constant” and “readonly” variables in C#

Initialization

  • const Must be initialized at the declaration only.
  • readonly Field Can be initialized at the declaration or within the constructor(s) of the class.

 

Evaluation Time

  • const  Evaluated at compile-time.
  • readonly Field Evaluated at runtime.

 

Data Type

  • const  Only allowed for primitive types (numeric types, bool, char, string) and enum.
  • readonly FieldCan be used with any data type (primitive types, custom objects, structs, etc.)

 

Scope

  • const  are Implicitly static. Belongs to the type, not an instance. You can't use static explicitly with const.
  • readonly FieldCan be static or instance-level. If instance-level, each instance of the class can have a different readonly value.

 

Access

  • const  Accessed directly using the class name (e.g., MyClass.MY_CONSTANT).
  • readonly Field Accessed using the class name if static (e.g., MyClass.MyStaticReadonlyField) or through an instance if instance-level (e.g., myObject.MyInstanceReadonlyField).

 

Runtime Value

  • const  value is "baked into" the compiled code wherever it's used. If you change a const in a library and recompile, consuming assemblies must also be recompiled to pick up the new value.
  • readonly Field value is determined at runtime. If you change a readonly in a library and recompile, consuming assemblies do not need to be recompiled (they will pick up the new value at runtime).

 

Use Cases

  • const  are Fixed, unchanging values known at compile time (e.g., Math.PI, DaysInWeek, MaxUsers).
  • readonly Field Values that are initialized once (either at declaration or in the constructor) and then remain constant for the lifetime of the object or application. Useful for configuration settings, dependencies, or values that depend on runtime conditions.

 

Implicit Static

  • Yes
  • No (must be explicitly static for static behavior)

Related Question