Nullable<long> is not Nullable<long> after assignment from long

Viewed 227

I have an unexpected behaviour with nullables on primitives.

My test code:

Nullable<long> value = long.Parse("5");
Type type = value.GetType();
// at this Point type is System.Int64 and not Nullable<System.Int64>

Is there any possibility, where value stays a Nullable<System.Int64> and does not get converted to a regular long?

2 Answers

No. You have already assigned it to a long? variable.

When you call GetType(), this function is defined on System.Object. Therefore to call it, we must box the value.

You can see this by viewing the generated MSIL instructions for the GetType() call:
box System.Nullable<System.Int64>
call System.Object.GetType
So when it is boxed it actually pushes the long? on the stack, and the boxing only gives us a boxed long

Hence the resulting value, in the case of a nullable, is the base type (see here and here).

In this instance, there is no reason to call GetType anyway, because we know it's a long?

When you look at the docs long.Parse returns long, not long?.

public static long Parse (string s);

You can of course convert that to a long?, but that doesn´t change that statement.

long a = long.Parse("5");
Nullable<long> n = a; // convert to long?

So in short there´s no way long.Parse will ever return something different than a long. Even when you provide some invalid input:

long a = long.Parse("Hello"); //throws FormatException

Calling GetType on your variable will give you the runtime-type, not the compile-time one. As Parse returns a long at runtime, GetType surely does also.

Related