Search code examples
c#disassemblycil

Is this CIL valid?


Let 0 be a variable of type object. Assume that it's value is null. Let 1 be a variable of type Boolean.

Is the CIL:

ldloc 0
stloc 1

valid? If it is valid, is there C# that can compile to this?


Solution

  • I don't think that can be valid, because the sizes are different - in particular on x64. To quote from stloc:

    The type of the value must match the type of the local variable as specified in the current method's local signature.

    For a null test, I think you want:

    ldloc.0 
    ldnull
    ceq
    

    which will return 1 if it is null, 0 otherwise. To invert this, perhaps:

    ldc.i4.0
    ldloc.0 
    ldnull
    ceq
    ceq
    stloc.1  
    

    edit: I tested the following:

    object o = GetObj();
    bool b = o != null;
    

    and the compiler emits:

    ldloc.0 
    ldnull 
    cgt.un 
    stloc.1  
    

    So maybe cgt.un is all you need here!