Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using == or .Equals() for bool comparison

Tags:

c#

I was reviewing some code, and I found something that looked like this:

public class MyClass
{
    public bool IsEditable { get; set; }

    public void HandleInput()
    {
        if (IsEditable.Equals(false))
        {
            //do stuff
        }
    }
}

As far as I know, (IsEditable.Equals(false)) is identical to (IsEditable == false) (and also the same as (!IsEditable)).

Besides personal preference, is there any difference at all between .Equals() and ==, specifically when used to compare bools?

like image 1000
Ryan Kohn Avatar asked Nov 28 '12 21:11

Ryan Kohn


2 Answers

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.

like image 100
Sam I am says Reinstate Monica Avatar answered Oct 17 '22 19:10

Sam I am says Reinstate Monica


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
like image 45
Oliver Hanappi Avatar answered Oct 17 '22 20:10

Oliver Hanappi