
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
278
|
Chapter 4: Generics
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 parame-
ter 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);