|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)
Constants are immutable values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const. For a list of the built-in types, see Built-In Types Table (C# Reference). User-defined types, including classes, structs, and arrays, cannot be const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.
C# does not support const methods, properties, or events.
The enum type enables you to define named constants for integral built-in types (for example int, uint, long, and so on). For more information, see enum (C# Reference).
Constants must be initialized as they are declared. For example:
In this example, the constant months is always 12, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference and cannot appear as an l-value in an expression.
Use caution when you refer to constant values defined in other code such as DLLs. If a new version of the DLL defines a new value for the constant, your program will still hold the old literal value until it is recompiled against the new version.
Multiple constants of the same type can be declared at the same time, for example:
The expression that is used to initialize a constant can refer to another constant if it does not create a circular reference. For example:
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 because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. For example:
For more information, see the following section in the C# Language Specification: