Generic method to instantiate a variable of any ty

2019-09-07 08:11发布

问题:

Let's say I have this function which instantiates a new variable with default/empty value for any type

public static T GetDefault<T>() where T : new() //body of this method is the question
{
    T t = new T();
    return t;
}

The problem with the above function is when I have something like int? for T. Because if I have

int? t = new int?();

t will be null! I do not want this to happen, instead I want the default value of int to be returned which is 0.

To solve this, I can have different overloads of GetDefault function for int?, bool? etc but that's not elegant. I can also check internally in the function if type is int? or bool? etc, but how would I go about instantiating it's base type?

Or the question boils down to how to identify if T is nullable struct and accordingly how to instantiate the nullable struct..

回答1:

Type realType = Nullable.GetUnderlyingType(typeof(T));
t = (T)Activator.CreateInstance(realType ?? typeof(T));