4.13 Initialize generic variables to their default values
Problem
Your generic class contains a variable whose type is the same as the type parameter defined in the class. When you construct a generic class, you want the variable to be initialized to its default value.
Solution
Simply use the default keyword to initialize the 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>();
// 检查成员data是否已经被设置为它的默认值; 返回true.
bool isDefault = dv.IsDefaultData();
Console.WriteLine("Initial data: " + isDefault);
// 设置成员data.
dv.SetData(100);
// 再次检查, 这次返回false.
isDefault = dv.IsDefaultData();
Console.WriteLine("Set data: " + isDefault);
The first call to Isdefaultdata returns True, and the second call returns FALSE, and the output is as follows:
Initial Data:true
Set Data:false
Discuss
When initializing a variable of the same type as a generic type parameter, you cannot simply set it to null. What happens when a type parameter is a value type such as int or char? This will not work because the value type cannot be null. You might think of nullable types, such as long? Or nullable<long> can be set to null (reference tip 4.7 To learn more about nullable types). However, the compiler has no way of knowing what type of arguments will be used to construct the type. (Translator Note: This means that the compiler does not know whether the user is using a value type or a reference type, because the nullable type is only for the value type)
The default keyword allows you to tell the compiler that this variable will be used at compile time. If a type argument provides a numeric value (such as Int,long,decimal), the default value is 0. If the type argument provides a reference type, the default value is null. If a type argument provides a struct, the default value of the struct initializes each member of it: The numeric type is 0 and the reference type is null.