
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Initializing Generic Variables to Their Default Values
|
279
// Check again, this time a false is returned.
isDefault = dv.IsDefaultData( );
Console.WriteLine("Set data: " + isDefault);
}
The first call to IsDefaultData returns true, while the second returns false. The out-
put is shown here:
Initial data: True
Set data: False
Discussion
When initializing a variable of the same type parameter as the generic class, you can-
not just set that variable to
null. What if the type parameter is a value type such as
an int or char? This will not work since value types cannot be null. You may be
thinking that a nullable type such as
long? or Nullable<long> can be set to null (see
Recipe 4.7 for more on nullable types). However, the compiler has no way of know-
ing what type argument the user will use to construct the type.
The
default keyword allows you to tell the compiler that at compile time the default
value of this variable should be used. If the type argument supplied is a numeric
value (e.g.,
int, long, decimal), then the default value is zero. If the type argument
supplied is a reference type, then the default value is
null. If the type argument sup-
plied is a
struct, then the default value of the struct is determined by initializing
each member field of the
struct to zero for numeric types or ...