Skip to main content

Command Palette

Search for a command to run...

C# : Constants vs Readonly Fields

Published
•3 min read•View as Markdown

In C#, both constants and readonly fields are used to store values that should not change after assignment, but they differ in how and when their values are set, as well as how they are handled by the compiler. Understanding these differences is key to using them effectively.

1. Constants (const)

  • Definition: Constants are immutable values that are known and assigned at compile-time. It means const variable must be assigned during its declaration.

  • Syntax: Declared with the const keyword.

  • Initialization: Must be assigned when declared and cannot be modified thereafter.

  • Scope: They are static by nature, meaning they belong to the type (class) rather than an instance.

  • Usage: Typically used for values that are fundamental and unchanging, like mathematical constants or configuration parameters.

Example:

public class MathConstants
{
    public const double Pi = 3.14159;
}

Key Points:

  • Constants are inlined at the call site. If the value of a constant is changed in a new version of the library, clients using the old version will still see the old value.

  • Only primitive data types (like int, double, bool, string, etc.) and enums can be const.

2. Readonly Fields (readonly)

  • Definition: Readonly fields can be assigned either at compile-time or at runtime, but once assigned, they cannot be changed.

  • Syntax: Declared with the readonly keyword.

  • Initialization: Readonly fields can be initialized either during their declaration or inside the constructor of the class.

  • Scope: They can be instance-specific or static.

  • Usage: Used for values that are assigned once (typically in the constructor) but can be based on runtime logic.

  • a readonly field does not have to be assigned during variable declaration. It can be assigned in either of two places:

    1. At the point of declaration (optional).

    2. In a constructor (mandatory if not assigned at declaration).

This flexibility allows you to initialize the readonly field during object creation, making it ideal for scenarios where the value isn't known until runtime.

Example:

public class Circle
{
    public readonly double Radius;
    public static readonly double Pi = 3.14159;

    public Circle(double radius)
    {
        Radius = radius;
    }
}

Key Points:

  • Unlike const, readonly fields can hold references to non-primitive types (like objects, arrays, or user-defined types).

  • If a field is static readonly, it’s assigned once when the class is loaded, and for instance fields, it’s assigned when the object is created.

  • The value of a readonly field can vary across instances if it’s an instance field and initialized in the constructor.

Key Differences:

FeatureConstReadonly
Time of AssignmentCompile-timeRuntime or constructor
Mutable in Constructor?NoYes
Type ScopeAlways staticCan be static or instance
Type LimitationsPrimitives, enums, and string onlyAny type (including reference types)
Memory AllocationStored directly in code (inlined)Stored in memory as part of the class instance

When to Use:

  • Use const when:

    • The value is truly constant (like Pi, MaxValue, etc.).

    • You want the best performance (since the value is inlined).

    • You are dealing with simple types (primitives and strings).

  • Use readonly when:

    • The value is not known until runtime (e.g., configurations, user input).

    • You need to initialize the value in a constructor.

    • You are working with complex types or need flexibility with instantiation.