C# - Constants

Constants

A constant is another type of field. It holds a value that is assigned when the program is compiled, and never changes after that. Constants are declared using the const keyword. Only the C# built-in types (excluding System.Object) may be declared as const.

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.

Constants must be initialized as they are declared.

Literal Constants

A literal constant is just a value. For example, 32 is a literal constant. It does not have a name; it is just a literal value. And you can't make the value 32 represent any other value. The value of 32 is always 32. You can't assign a new value to 32, and you can't make 32 represent the value 99 no matter how hard you might try. You'll use literal Constants a lot, but you probably won't think of them as such.

Symbolic Constants

Symbolic Constants assign a name to a constant value. You declare a symbolic constant using the following syntax:

const type identifier =value;

The const keyword is followed by a type, an identifier, the assignment operator (=), and the value to assign to the constant.

This is similar to declaring a variable except that you start with the keyword const and symbolic Constants must be initialized. Once initialized, a symbolic constant cannot be altered. For example, in the following declaration, 32 is a literal constant and FreezingPoint is a symbolic constant of type int:

const int FreezingPoint = 32;