CSharp/C# Tutorial - C# Constants

A constant is a static field whose value can never change.

A constant is evaluated statically at compile time.

A constant can be any of the built-in numeric types, bool, char, string, or an enum type.

A constant is declared with the const keyword and must be initialized with a value.

For example:

public class Test { 
    public const string Message = "Hello World"; 

A constant is much more restrictive than a static readonly field.

A constant differs from a static readonly field in that the evaluation of the constant occurs at compile time.

For example:

public static double Circumference (double radius) {
    return 2 * System.Math.PI * radius; 

is compiled to:

public static double Circumference (double radius) {
    return 6.283 * radius; 

A static readonly field can have a different value per application.

Constants can also be declared local to a method. For example:

static void Main() { 
    const double twoPI = 2 * System.Math.PI; 

Non-local constants allow the following modifiers:

Access modifierspublic internal private protected
Inheritance modifiernew