C# – how to assign a default value to generic type var

In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:

  • Whether T will be a reference type or a value type.
  • If T is a value type, whether it will be a numeric value or a struct.

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable<T>, which is initialized like any struct.


// Suppose T is the type of data stored in a particular instance of 'SomeClass'
public class SomeClass<T>
{
    // ...

    public T SomeMethod()
    {
        // The following declaration initializes temp to the appropriate 
        // default value for type T.
        T temp = default(T);

        // Do something...

        return temp;
    }
}    // End of SomeClass...

Despite being so simple, often we tend to forget when you rarely use.

Share            
X
                                                                                                        

Leave a Reply

Your email address will not be published. Required fields are marked *