Share via


Constants (C# Programming Guide) 

Classes and structs can declare constants as members. Constants are values which are known at compile time and do not change. (To create a constant value that is initialized at runtime, use the readonly keyword.) Constants are declared as a field, using the const keyword before the type of the field. Constants must be initialized as they are declared. For example:

class Calendar1
{
    public const int months = 12;
}

In this example, the constant months will always be 12, and cannot be changed — even by the class itself. Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

Multiple constants of the same type can be declared at the same time, for example:

class Calendar2
{
    const int months = 12, weeks = 52, days = 365;
}

The expression used to initialize a constant can refer to another constant so long as it does not create a circular reference. For example:

class Calendar3
{
    const int months = 12;
    const int weeks = 52;
    const int days = 365;

    const double daysPerWeek = days / weeks;
    const double daysPerMonth = days / months;
}

Constants can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the constant. For more information, see Access Modifiers (C# Programming Guide).

Constants are accessed as if they were static fields, although they cannot use the static keyword. Expressions that are not contained within the class defining the constant must use the class name, a period, and the name of the constant to access the constant. For example:

int birthstones = Calendar.months;

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 10.3 Constants

See Also

Reference

Objects, Classes and Structs (C# Programming Guide)
Properties (C# Programming Guide)
Data Types (C# Programming Guide)
readonly (C# Reference)

Concepts

C# Programming Guide