Please see my comment in the code below. How should I check for the parameter to be null? It looks like null is being casted to Foo which essentially makes a recursive call the the == operator. Why does this happen?
public class Foo
{
public static bool operator ==(Foo f1, Foo f2)
{
if (f1 == null) //This throw a StackOverflowException
return f2 == null;
if (f2 == null)
return f1 == null;
else
return f1.Equals((object)f2);
}
public static bool operator !=(Foo f1, Foo f2)
{
return !(f1 == f2);
}
public override bool Equals(object obj)
{
Foo f = obj as Foo;
if (f == (Foo)null)
return false;
return false;
}
public override int GetHashCode()
{
return 0;
}
}
Because the language rules say to.
You’ve provided an operator with this signature:
and then – wherever this happens to be in code – you’ve got this expression:
where
f1has a compile-time type ofFoo. Nownullis implicitly convertible toFooas 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:
==meant when it’s used within a declaration for==. Ick.==expression with one operand beingnullalways meant the reference comparison.Neither is particularly nice, IMO. Avoiding it is simple though, avoids redundancy, and adds an optimization:
However, you then need to fix your
Equalsmethod, 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:
Note that this allows you to only bother with nullity checks in one place. In order to avoid redundantly comparing
f1for null when it’s been called via an instance method ofEqualsto start with, you could delegate from==toEqualsafter checking for nullity off1, but I’d probably stick to this instead.