GetType in Nullable Boolean

I was looking for nullable bools when I found this article on Microsoft MSDN

How to identify a null type (C # programming guide)

You can use a C # type operator to create a Type object that represents a Nullable type.

So, I tried checking with nullable bool:

Console.Write(typeof(bool?)); //System.Nullable`1[System.Boolean]

The MSDN article says:

You can also use the classes and methods of the System.Reflection namespace to generate type objects that represent Nullable types. However, if you try to get type information from Nullable variables at run time using the GetType method or the is operator, the result is a Type object that represents the base type, not the Nullable type itself.

Calling GetType of type Nullable invokes a boxing operation when the type is implicitly converted to Object. Therefore, GetType always returns a Type object that represents the base type, not the Nullable type.

If this is true, I expect to get the same result from .GetType()if I use a nullable bool or a regular bool. But this is not what happens:

    bool a = new bool();
    Console.Write(a.GetType()); //Prints System.Boolean

    bool? b = new bool?();
    Console.Write(b.GetType()); //Exception!

Ruled out:

An unhandled exception of type "System.NullReferenceException" occurred in BoolTest.exe

Additional information: The reference to the object is not installed in the instance of the object.

But the reference to the object is set by the instance of the object. What could be causing this error?

+4
source share
2 answers

GetType NULL ( Nullable Type ).

bool? b = new bool?(); bool? b = null;

, :

bool? b = new bool?(false);
Console.Write(b.GetType()); // System.Boolean

, GetType() Nullable, (Not Null). , System.Boolean. - , NULL, , .

= null new bool?(), Fiddle. IL:

IL_0001:  ldloca.s   V_0
IL_0003:  initobj    valuetype [mscorlib]System.Nullable`1<bool>

IL_0009:  ldloca.s   V_1
IL_000b:  initobj    valuetype [mscorlib]System.Nullable`1<bool>
+4

:

Nullable<T> , , bool? b = new bool?();, b, GetType(), a NullReferenceException? new , b null?

, . Nullable<T> . #:

4.1.10

[...]

T? :

  • HasValue bool
  • T

, HasValue , . , . , HasValue , null. undefined. System.InvalidOperationException.

, , bool? b = new bool?(); : HasValue on. false, .

:

4.3.1

: nullable-type , null (HasValue )

MSDN: Nullable Types ( #):

, , , . HasValue , null .

:

11.3.5

, System.Object(, Equals, GetHashCode ToString), struct .

GetType() Nullable<T>, . GetType() , . null Nullable<T> (object)null. .

. .NET?.


, :

  • b , Nullable<bool> HasValue false.
  • GetType() , Nullable<bool> object.GetType().
  • , (object)null.
  • ((object)null).GetType(), NullReferenceException, .

, , null Nullable<T>, - :

Type GetType<T>(T obj) 
{ 
    return typeof(T); 
}

:

Console.WriteLine(GetType(b));
+5

Source: https://habr.com/ru/post/1648931/


All Articles