Information Technology Reference
In-Depth Information
Explicit and Implicit Field Initialization
Since a field is a kind of variable, the syntax for a field initializer is the same as that of the vari-
able initializer in the previous chapter.
￿A field initializer is part of the field declaration, and consists of an equals sign followed
by an expression that evaluates to a value.
￿
The initialization value must be determinable at compile time.
class MyClass
{
int F1 = 17 ;
}
Field initializer
￿
If no initializer is used, the value of a field is set by the compiler to a default value, deter-
mined by the type of the field. The default values for the simple types are given in
Table 4-1. The default for reference types is null .
For example, the following code declares four fields. The first two fields are initialized
implicitly. The second two fields are initialized explicitly with initializers.
class MyClass
{
int F1; // Initialized to 0 - value type
string F2; // Initialized to null - reference type
int F3 = 25; // Initialized to 25
string F4 = "abcd"; // Initialized to "abcd"
}
Declarations with Multiple Fields
As with variables, you can declare multiple fields of the same type in the same statement by sep-
arating the names with commas. Different types cannot be mixed in a single declaration. For
example, you can combine the four preceding declarations into two statements, with the exact
same semantic result:
int F1, F3 = 25;
string F2, F4 = "abcd";
Search WWH ::




Custom Search