Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using the == operator and the Equals method on a boxed boolean type?

Tags:

c#

boxing

Given these two statements...

((object)false) == ((object)false)
((object)false).Equals((object)false)

The first statement returns false. The second statement returns true.

I understand why the first statement returns false - when the boolean is boxed, it becomes a reference type, and the two references are not equal. But, why / how does the second statement result in true?

like image 500
carmbrester Avatar asked Mar 01 '11 17:03

carmbrester


1 Answers

Because it's still calling the polymorphic Equals method, basically.

Sample code to demonstrates with a different type:

using System;

struct Foo
{
    public override bool Equals(object other)
    {
        Console.WriteLine("Foo.Equals called!");
        return true;
    }

    public override int GetHashCode()
    {
        return 1;
    }
}

class Program
{
    static void Main(string[] args)
    {
        object first = new Foo();
        object second = new Foo();
        first.Equals(second);
    }
}

That still prints "Foo.Equals called!" because calling the Equals method on the "box" still calls Foo.Equals.

Now == isn't overridden, it's overloaded... so if you write:

object first = ...;
object second = ...;
bool same = first == second;

That will always compare for reference identity, without ever running any type-specific code.

like image 72
Jon Skeet Avatar answered Nov 15 '22 06:11

Jon Skeet