Constants and Read-Only Fields

Learn to create fields that are read-only.

Constants

A constant is an immutable field with a value assigned during compilation. Constants can’t be reassigned and their value can’t be modified.

Constants are declared using the const keyword:

public const int PI = 3.14;

Only the primitive types, except for the Object class, can be declared as constants. Any other classes, including user-defined types, can’t be modified with the const keyword.

Access modifiers can be used to control access to constants. The static keyword, however, isn’t allowed, because const fields are static members.

The difference between normal static fields and constants is that constants are assigned a value during compilation, and this value doesn’t change during runtime. In contrast, the initial assignment for regular static fields happens during program launch.

Consider the following code snippet:

public class SomeClass 
{
    public const int number = 5;
    public static int number1 = 7;
}

Using a special tool (ILDasm), we can see the resulting IL code (in this case, some part of it):

.class public auto ansi beforefieldinit SomeClass
    extends [System.Private.CoreLib]System.Object
{
    // Fields
    .field public static literal int32 number = int32(5)
    .field public static int32 number1

.method private hidebysig specialname rtspecialname static 
        void .cctor () cil managed 
    {
        // Method begins at RVA 0x2058
        // Code size 7 (0x7)
        .maxstack 8

        IL_0000: ldc.i4.7
        IL_0001: stsfld int32 SomeClass::number1
        IL_0006: ret
    } // end of method SomeClass::.cctor

} // end of class SomeClass

The only thing that we need to understand from the code above is that the value of the number constant is assigned during compilation, while number1 receives its value when the static constructor is called. Here’s the explanation:

Get hands-on with 1400+ tech skills courses.