Why does this happen?
Because the language rules say to.
You've provided an operator with this signature:
public static bool operator ==(Foo f1, Foo f2)
and then - wherever this happens to be in code - you've got this expression:
f1 == null
where f1
has a compile-time type of Foo
. Now null
is implicitly convertible to Foo
as well, so why wouldn't it use your operator? And if you've got the first line of your operator unconditionally calling itself, you should expect a stack overflow...
In order for this not to happen, you'd need one of the two changes to the language:
- The language would have to special-case what
==
meant when it's used within a declaration for ==
. Ick.
- The language would have to decide that any
==
expression with one operand being null
always meant the reference comparison.
Neither is particularly nice, IMO. Avoiding it is simple though, avoids redundancy, and adds an optimization:
public static bool operator ==(Foo f1, Foo f2)
{
if (object.ReferenceEquals(f1, f2))
{
return true;
}
if (object.ReferenceEquals(f1, null) ||
object.ReferenceEquals(f2, null))
{
return false;
}
return f1.Equals(f2);
}
However, you then need to fix your Equals
method, because that then ends up calling back to your ==
, leading to another stack overflow. You've never actually ended up saying how you want equality to be determined...
I would normally have something like this:
// Where possible, define equality on sealed types.
// It gets messier otherwise...
public sealed class Foo : IEquatable<Foo>
{
public static bool operator ==(Foo f1, Foo f2)
{
if (object.ReferenceEquals(f1, f2))
{
return true;
}
if (object.ReferenceEquals(f1, null) ||
object.ReferenceEquals(f2, null))
{
return false;
}
// Perform actual equality check here
}
public override bool Equals(object other)
{
return this == (other as Foo);
}
public bool Equals(Foo other)
{
return this == other;
}
public static bool operator !=(Foo f1, Foo f2)
{
return !(f1 == f2);
}
public override int GetHashCode()
{
// Compute hash code here
}
}
Note that this allows you to only bother with nullity checks in one place. In order to avoid redundantly comparing f1
for null when it's been called via an instance method of Equals
to start with, you could delegate from ==
to Equals
after checking for nullity of f1
, but I'd probably stick to this instead.