IL fun fact: not is not ! 30 Jan 2012


Picture yourself working on crafting a specific piece of CIL. You need to write the compiled equivalent of:
bool b = ...;
bool n = !b;
It would be tempting to write:
ldloc b
not
stloc n
Except that it would not always work. not doesn't negate booleans, it computes the bitwise complement of the value on the stack. It's also not to be confused with the neg opcode, which negates a value, as in a multiplication by -1. The usual pattern to negate a boolean is:
ldloc b
ldc.i4.0
ceq
stloc n
But that's not really fun, is it? Actual fun fact: there's a misused “not” in the ECMA 335 in the example of the section 14.5 of the partition II.