Information Technology Reference
In-Depth Information
Constants
Of the nine class member types, two of them are
data
member types. The first, which has
already been discussed, is fields. The second is
constants
. You can think of a
constant
as a type
of “variable” for which the value cannot be changed.
A constant
must be initialized
at its declaration.
A constant
cannot be changed
after its declaration.
There are two kinds of constants:
-
Member constants, which are like fields—except constant
-
Local constants, which are like local variables—except constant
The core declaration for a constant is shown following. Note that the syntax is the same as
that of a field or variable declaration, except for the following:
The addition of the keyword
const
in front
The mandatory initializer
■
Note
The keyword
const
is not a modifier, but part of the core declaration. It must be placed immediately
before the type.
Keyword
↓
const
Type
Identifier
= Value
;
↑
Initializer required
■
Note
Unlike C and C++, in C# there are no global constants. Every constant must be declared within
a type.