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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With