Information Technology Reference
In-Depth Information
Constant members, like fields, are declared in the class declaration, as follows:
class MyClass
{
const int IntVal = 100 ; // Defines a constant named IntVal, of type int
// and initializes its value to 100
} Type Initializer
const double PI = 3.1416; // Error: cannot be declared outside a type
// declaration
The value used to initialize a constant must be computable at compile time.
class MyClass
{
const int IntVal1 = 100;
const int IntVal2 = 2 * IntVal1; // Fine. The value of IntVal1 was
} // set in the previous line
You cannot assign to a constant after its declaration.
class MyClass
{
const int IntVal; // Error: initialization is required.
IntVal = 100; // Error: assignment is not allowed.
}
Constants Are Like Statics
Constants members act like static values. They are “visible” to every instance of the class, and
they are available even if there are no instances of the class.
For example, the following code declares class X with constant field PI . Main does not cre-
ate any instances of X , and yet it can use field PI and print its value.
class X
{
public const double PI = 3.1416;
}
class Program
{
static void Main()
{
Console.WriteLine("pi = {0}", X.PI); // Use static field PI
}
}
Search WWH ::




Custom Search