Recipe4.13.Initializing Generic Variables to Their Default Values


Recipe 4.13. Initializing Generic Variables to Their Default Values

Problem

You have a generic class that contains a variable of the same type as the type parameter defined by the class itself. Upon construction of your generic object, you want that variable to be initialized to its default value.

Solution

Simply use the default keyword to initialize that 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 code to use this class is shown here:

 public static void ShowSettingFieldsToDefaults() {     DefaultValueExample<int> dv = new DefaultValueExample<int>();     // Check if the data is set to its default value; true is returned.     bool isDefault = dv.IsDefaultData();     Console.WriteLine("Initial data: " + isDefault);     // Set data.     dv.SetData(100);     // 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 output is shown here:

 Initial data: True Set data: False 

Discussion

When initializing a variable of the same type parameter as the generic class, you cannot 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 knowing 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 supplied 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 null for reference types.

See Also

See Recipe 4.7; see the "default Keyword in Generic Code" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net