Whats the use of Nullable.GetUnderlyingType, if typeof(int?) is an Int32?

前端 未结 5 2172
萌比男神i
萌比男神i 2021-02-05 16:07

why is typeof int? an Int32

int? x = 1;
Console.WriteLine(x.GetType().Name);

If it is okay then what\'s the use of

5条回答
  •  忘掉有多难
    2021-02-05 16:28

    Calling GetType() boxes your variable. The CLR has a special rule that Nullable gets boxed to T. So x.GetType will return Int32 instead of Nullable.

    int? x = 1;
    x.GetType() //Int32
    typeof(int?) //Nullable
    

    Since a Nullable containing null will be boxed to null the following will throw an exception:

    int? x = null;
    x.GetType() //throws NullReferenceException
    

    To quote MSDN on Boxing Nullable Types:

    Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, the object reference is assigned to null instead of boxing

    If the object is non-null -- if HasValue is true -- then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable that wraps the value type.

提交回复
热议问题