Constants

suggest change

In C#, a constant is an immutable value known at compile time that cannot be modified throughout the lifetime of the program. C# provides the const keyword for compile-time constants and the readonly keyword for runtime constants.


1. Declaring const Values

Constants are declared using the const modifier and must be initialized at their point of declaration with a compile-time constant expression:

public class MathConstants
{
    // Class-level compile-time constants
    public const double Pi = 3.141592653589793;
    public const int MaxRetries = 3;
    public const string DefaultApiVersion = "v1";
}

You can also declare local constants inside methods:

public void ProcessData()
{
    const int bufferSize = 4096;
    byte[] buffer = new byte[bufferSize];
    // bufferSize = 8192; // Compilation error: The left-hand side of an assignment must be a variable, property or indexer
}

Allowed Types for const

Compile-time constants are restricted to:


2. Compile-Time Inlining and Versioning Risks

When the C# compiler compiles code referencing a const from another assembly, it bakes (inlines) the literal value directly into the calling assembly's IL. It does not emit a reference to the field.

The Versioning Pitfall

Consider a shared library SharedConfig.dll:

// Assembly A (SharedConfig.dll)
public static class AppLimits
{
    public const int MaxConnections = 100;
}

And a consumer application:

// Assembly B (ConsumerApp.exe)
Console.WriteLine(AppLimits.MaxConnections); // Compiled directly as ldc.i4 100

If SharedConfig.dll is updated to MaxConnections = 200 and replaced on disk without recompiling ConsumerApp.exe, ConsumerApp.exe will continue using the old value (100).


3. const vs. static readonly

To avoid the compile-time inlining issue and allow non-primitive types or runtime calculation, use static readonly:

Feature const static readonly
Evaluation Time Compile time Runtime (at type initialization)
Memory Allocation Inlined as literal; no memory slot Dedicated static field in memory
Supported Types Primitives, enums, strings, null Any valid C# type
Modifiable via Constructor Never Inside static constructor
Cross-Assembly Inlining Inlined into caller assembly Referenced by metadata; safe across updates
public class ServiceSettings
{
    // Evaluated at runtime; safe across assembly boundaries
    public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(30);
    public static readonly DateTime AppLaunchTime = DateTime.UtcNow;

    // Complex object instance
    public static readonly HttpClient SharedClient = new HttpClient();
}

4. Constant Interpolated Strings (C# 10+)

Starting with C# 10, string interpolation can be used in const declarations provided all placeholder expressions are also compile-time constant strings:

public static class Endpoints
{
    public const string BaseUrl = "https://api.example.com";
    public const string Version = "v2";

    // Valid compile-time constant interpolated string
    public const string UsersEndpoint = $"{BaseUrl}/{Version}/users";
    public const string OrdersEndpoint = $"{BaseUrl}/{Version}/orders";
}

5. Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents