Using == or .Equals() for bool comparison

In fact, for basic types such as int, bool etc. there is a difference between calling Equals() and == due to the fact that the CIL has instructions for handling such types. Calling Equals() forces boxing of the value and making a virtual method call, whereas usage of == leads to usage of a single CIL instruction.

!value and value == false is actually the same, at least in Microsoft's C# compiler bundled with .NET 4.0.

Hence, the comparisons within the following methods

public static int CompareWithBoxingAndVirtualMethodCall(bool value)
{
    if (value.Equals(false)) { return 0; } else { return 1; }
}

public static int CompareWithCILInstruction(bool value)
{
    if (value == false) { return 0; } else { return 1; }
    if (!value) { return 0; } else { return 1; } // comparison same as line above
}

will compile to to the following CIL instructions:

// CompareWithBoxingAndVirtualMethodCall

ldarga.s 'value'
ldc.i4.0
call instance bool [mscorlib]System.Boolean::Equals(bool) // virtual method call
brfalse.s IL_000c // additional boolean comparison, jump for if statement

// CompareWithCILInstruction

ldarg.0
brtrue.s IL_0005 // actual single boolean comparison, jump for if statement

This is mostly a readability issue. I'd normally use == because that's what I'm used to looking at.

Specifically with bools, you don't have to compare them at all

if(!IsEditable)

will suffice

although, Sometimes I myself do write things like if (val == false) just to be extra sure that i don't misread it when i have to modify the code.

Tags:

C#