简体   繁体   中英

Generic method to instantiate a variable of any type (including nullable struct)?

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..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM