Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

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;

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

  • 10.3 Constants

© 2015 Microsoft