News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

C# Tutorial – 25 – Constants

A variable in C# can be made into a compile-time constant by adding the const keyword before the data type. This modifier means that the variable cannot be changed and it must therefore be assigned a value at the same time as it is declared. Any attempts to assign a new value to the constant will result in a compile-time error.

Local constants

A local constant must always be initialized at the same time as it is declared.

static void Main()
{
  const int a = 10; // compile-time constant
}

The const modifier creates a compile-time constant, and so the compiler will replace all usage of the constant with its value. The assigned value must therefore be known at compile-time. As a result of this, the const modifier may only be used together with the simple types, as well as with enum and string types.

Constant fields

The const modifier can be used on fields as well as on local variables. Unlike C++, C# does not allow method parameters to be made constant.

class MyClass
{
  const int b = 5; // compile-time constant field
}

A field that is marked with const is accessed as if it was a static field. Constant fields cannot be made static.

int c = MyClass.b;

Readonly keyword

Another variable modifier similar to const is readonly, which creates a run-time constant. This modifier may only be applied to fields, and like const it makes the field unchangeable.

class MyClass
{
  readonly int d = 3; // run-time constant field
}

However, since a readonly field is assigned at run-time it can be assigned a dynamic value that is not known until run-time.

readonly int e = System.DateTime.Now.Hour;

Unlike const, readonly can be applied to any data type.

readonly int[] f = { 1, 2, 3 };

In addition, a readonly field cannot only be initialized when it is declared. It can alternatively be assigned a value in the constructor.

class MyClass
{
  readonly string s;
  public MyClass() { s = "Hello World"; }
}

Constant guideline

In general, it is a good idea to always declare variables as constants if they do not need to be reassigned. This ensures that the variables will not be changed anywhere in the program by mistake, which in turn helps to prevent bugs.