Objects based on types with a null value, only in boxing, if the object is not equal to zero

I created a simple program C#:

class Program
{
    static void Main(string[] args)
    {
        Int32? a = null;
        object x = a;
    }
}

According to MSDN:

Objects based on types with a null value are placed only in the box , if the object is not equal to zero. If HasValue is false, the reference to the object is null instead of the box .

I tried my executable in ILDASMand noticed that the code was ILcalling the box method.

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       17 (0x11)
  .maxstack  1
  .locals init ([0] valuetype [mscorlib]System.Nullable`1<int32> a,
           [1] object x)
  IL_0000:  nop
  IL_0001:  ldloca.s   a
  IL_0003:  initobj    valuetype [mscorlib]System.Nullable`1<int32>
  IL_0009:  ldloc.0
  IL_000a:  box        valuetype [mscorlib]System.Nullable`1<int32>
  IL_000f:  stloc.1
  IL_0010:  ret
} // end of method Program::Main

My question is: why was he called? Maybe I'm doing something wrong or misunderstanding?

+4
source share
2 answers

, - x null, null. , MSDN , :

Int32? a = null;
object x = a;
object y = a;
object.ReferenceEquals(x, y); // true

:

Int32? a = 3;
object x = a;
object y = a;
object.ReferenceEquals(x, y); // false

- , , a null - a , , , ( null).

+6

. Release, . :

.method private hidebysig static 

    void Main (string[] args
    ) cil managed 
{
    // Method begins at RVA 0x2054
    // Code size 11 (0xb)
    .maxstack 1
    .locals init (
        [0] valuetype [mscorlib]System.Nullable`1<int32>
    )
    IL_0000: ldloca.s 0
    IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
    IL_0008: ldloc.0
    IL_0009: pop
    IL_000a: ret
} // end of method C::Main

Int? null , Release box.

:

public void M(int? x) 
{
    object y = x;
    Console.WriteLine(y);
}
public void Main()
{
    M(null);
}

:

.method public hidebysig 
 instance void M (
        valuetype [mscorlib]System.Nullable`1<int32> x
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 12 (0xc)
    .maxstack 8

    IL_0000: ldarg.1
    IL_0001: box valuetype [mscorlib]System.Nullable`1<int32>
    IL_0006: call void [mscorlib]System.Console::WriteLine(object)
    IL_000b: ret
} // end of method C::M

.method public hidebysig 
 instance void Main () cil managed 
{
    // Method begins at RVA 0x2060
    // Code size 16 (0x10)
    .maxstack 2
    .locals init (
        [0] valuetype [mscorlib]System.Nullable`1<int32>
    )
    IL_0000: ldarg.0
    IL_0001: ldloca.s 0
    IL_0003: initobj valuetype [mscorlib]System.Nullable`1<int32>
    IL_0009: ldloc.0
    IL_000a: call instance void C::M(valuetype [mscorlib]System.Nullable`1<int32>)
    IL_000f: ret
} // end of method C::Main
+3

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


All Articles