mardi 14 avril 2015

Nullable create via reflection with HasValue = false, given a parameter of type `Type` only

Given a type parameter which is a Nullable<>, how can I create an instance of that type which has HasValue = false?


In other words, complete this code:



//type is guaranteed to be implement from Nullable<>
public static object Create(Type type)
{
//Instantatie a Nullable<T> with reflection whose HasValue = false, and return it
}


My attempt, which doesn't work (it throws a NullReferenceException) as there's no default constructor:



static void Main(string[] args)
{
Console.WriteLine(Create(typeof(Nullable<int>)));

Console.ReadLine();
}

//type is guaranteed to be implement from Nullable<>
public static object Create(Type type)
{
//Instantatie a Nullable<T> with reflection whose HasValue = false, and return it
return type.GetConstructor(new Type[0]).Invoke(new object[0]);
}





Aucun commentaire:

Enregistrer un commentaire