4.13 initialize generic variables as their default values
Problem
Your generic class contains a variable whose type is the same as the type parameter defined in the class. When constructing a generic class, you want this variable to be initialized as its default value.
Solution
You can use the default keyword to initialize a variable to its default value:
Public class defaultvalueexample <t>
{
T data = default (t );
Public bool isdefaultdata ()
{
T temp = default (t );
If (temp. Equals (data ))
{
Return (true );
}
Else
{
Return (false );
}
}
Public void setdata (T Val)
{
Data = val;
}
}
The following code uses this class:
Public static void showsettingfieldstodefaults ()
{
Defaultvalueexample <int> DV = new defaultvalueexample <int> ();
// Check whether the member data has been set as its default value; return true.
Bool isdefault = DV. isdefaultdata ();
Console. writeline ("initial data:" + isdefault );
// Set the member data.
DV. setdata (100 );
// Check again. This time, false is returned.
Isdefault = DV. isdefaultdata ();
Console. writeline ("Set Data:" + isdefault );
When isdefaultdata is called for the first time, true is returned, and false is returned for the second call. The output is as follows:
Initial Data: True
Set Data: false
Discussion
When initializing a variable of the same type as a generic type parameter, you cannot set it to null. What if the type parameter is a value type such as Int or Char? This will not work because the value type cannot be null. You may think of an empty type, such as long? Or nullable <long> can be set to null (refer to tip 4.7 For more information about the empty type ). However, the compiler does not know what type of arguments will be used to construct the type.(Note: The Compiler does not know whether the user uses the value type or the reference type, because the null type is only for the value type)
The default keyword allows you to tell the compiler that the default value of this variable will be used during compilation. If a real parameter of the type provides a numeric value (such as int, long, decimal), the default value is 0. If the type parameter provides the reference type, the default value is null. If a struct is provided for a type argument, the default value of the struct initializes each of its members. The numeric type is 0 and the reference type is null.
Reading reference
View tip 4.7. view the topic "Default keyword in generic code" in the msdn document.
(End)