Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable<long> is not Nullable<long> after assignment from long [duplicate]

Tags:

c#

.net

nullable

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?

like image 682
Arndt Bieberstein Avatar asked Nov 18 '25 23:11

Arndt Bieberstein


1 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?

like image 65
Charlieface Avatar answered Nov 21 '25 13:11

Charlieface