1

I need a Nullable type but how do I initialize such a variable? Whenever I try to do this it automatically converts to a normal Int32.

Nullable<Int32> nullableInt32 = new Nullable<Int32>(3);
Console.WriteLine(nullableInt32.GetType()); // gives me System.Int32

Is this a bug? How can I actually initalize the Nullable?

nino
  • 841
  • 1
  • 14
  • 30
  • 4
    (`int? nullableInt32 = 3` is a quicker way of writing what you needed...). The fun part here is that `GetType()` boxes the value type it's called on (as it's a non-virtual method defined on `object`), and a `Nullable` boxes to a normal `int`. So `GetType` ends up being called on a boxed `int`, and so returns `int`. This is just an annoying side-effect of `GetType`: you initialised a `Nullable` correctly. – canton7 Mar 23 '21 at 16:42

1 Answers1

5

From Microsoft's documentation:

If you want to determine whether an instance is of a nullable value type, don't use the Object.GetType method to get a Type instance to be tested with the preceding code. When you call the Object.GetType method on an instance of a nullable value type, the instance is boxed to Object. As boxing of a non-null instance of a nullable value type is equivalent to boxing of a value of the underlying type, GetType returns a Type instance that represents the underlying type of a nullable value type.

So your int? gets boxed to int, and GetType() is called on the boxed instance.

Unless you know the type at compile time and use typeof, there is no way to get a type of a nullable object:

var type = typeof(int?);

In practice this shouldn't matter because if you don't know the type at compile time, it means you're using some sort of type erasure (i.e. a cast to object), and that means boxing, and nullable value types don't exist there. You can't use polymorphism because that doesn't work with value types.

If you think you have a valid need for this, feel free to explain your use case in the comments.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • 1
    ("*there is no way to get a type of a nullable object*" -- strictly speaking you can do stuff like `typeof(int?).GetGenericTypeDefinition().MakeGenericType(someType)`, but like you said, why would you?) – canton7 Mar 23 '21 at 16:46
  • For particular reason why one would like to have instance of nullable type check plenty of similar questions like https://stackoverflow.com/questions/5644587/find-type-of-nullable-properties-via-reflection - after you get type of a property it is easier to compare it to value at hand than digging into type... – Alexei Levenkov Mar 23 '21 at 16:50