0

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:

public static Nullable<T> Create<T>() where T : struct 
{
    //Instantatie a Nullable<T> with reflection whose HasValue = false, and return it
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
Ian Newson
  • 7,679
  • 2
  • 47
  • 80
  • Apologies, I made a mistake asking this question and have reposted: http://stackoverflow.com/questions/29627013/nullable-create-via-reflection-with-hasvalue-false-given-a-parameter-of-type – Ian Newson Apr 14 '15 at 12:16
  • @Jamiec The two questions are different: one is `Create()`, while the other is `Create(Type type)`. While `return null` is a solution for both, the questions are surely different. – xanatos Apr 14 '15 at 12:35
  • @xanatos - this question should probably be deleted by the OP (In actual fact I tried to get him to just update this question - see below). In any case this question is now defunct and should no longer attract answers. Finally, feel free to cast a re-open vote if you disagree, im not the dictator off all things right ;) – Jamiec Apr 14 '15 at 13:12
  • @Jamiec I don't see why it couldn't still be helpful to someone else, which is why I didn't want to delete it. – Ian Newson Apr 14 '15 at 13:16

2 Answers2

3
return default(Nullable<T>) 

is enough.

or even

return null;

or even

return new Nullable<T>();

Nullable value types have the paradox that new Nullable<T>() == null

xanatos
  • 109,618
  • 12
  • 197
  • 280
2

No reflection needed in this case.

public static Nullable<T> Create<T>() where T : struct 
{
    return new Nullable<T>(); // or default(Nullable<T>) 
}

Live example: http://rextester.com/CHRRM73303

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • I made a mistake in my question. While your post answers the question it doesn't solve my problem so will have to start a new question. – Ian Newson Apr 14 '15 at 12:10
  • @IanNewson - or you could just update this question. – Jamiec Apr 14 '15 at 12:12
  • I've created the other question, it doesn't seem fair to change the existing question since it's not your fault your perfectly valid answer doesn't solve my problem. – Ian Newson Apr 14 '15 at 12:15