2

I have a method that check if 2 arguments are equal:

using System;

class Program{
    static void Main(string[] args){
        CheckEquality(false, false);
        Console.ReadKey();
    }
    public static void CheckEquality(object a, object b)
    {
        if (a == b){
            Console.WriteLine("yes");
        }else{
            Console.WriteLine("no");
        }
    }
}

As you can see, 2 arguments are "false", but when I run the program, the console says:

no
FSXplay
  • 31
  • 5
  • 6
    Since `a` and `b` are from reference class `Object`, operator== compares their address, not value. – wohlstad May 02 '22 at 12:01
  • 8
    Because you're not comparing values, you're comparing references to boxed objects containing Boolean values. The boolean values inside might be the same, but the `==` operator for `object` only compare references, and you have two distinct boxed objects, both containing `false` so the references are different. – Lasse V. Karlsen May 02 '22 at 12:01
  • 3
    You can try `if (a.Equals(b))` instead but beware that this does not handle `a` as a null reference. – Lasse V. Karlsen May 02 '22 at 12:03
  • 7
    Operators are not polymorphic, use if (a.Equals(b)) – Hans Passant May 02 '22 at 12:04

1 Answers1

3

You're actually not comparing values here.

You are comparing references. In this case references to object containing bool values.

So while the values inside the objects might be the same, the equals (==) operator for the object only compares the references, not the values. Since you have two distinct boxes the references are different, hence the result is false.

geertjanknapen
  • 1,159
  • 8
  • 23