Konrad Viltersten Konrad Viltersten - 4 months ago 21
C# Question

StackOverflow when designing comparison operators

According to this article, I've accompanied my Equal(Thing) as follows.

public override int GetHashCode() { return Id.GetHashCode(); }

public override bool Equals(object input)
{
Thing comparee = input as Thing;
return comparee != null && comparee.Id == Id;
}

public static bool operator ==(Thing self, Thing other)
{
return self != null && other != null && self.Id == other.Id;
}

public static bool operator !=(Thing self, Thing other)
{
return self == null || other == null || self.Id != other.Id;
}


The problem is that while it was working before I added the operator re-definitions, now I get StackOverflowException. What am I missing?

Answer

Once you define an == operator that compares Things, that'll be used when you say someThing == null. Likewise with !=.

So if you say self == other, you end up calling operator ==(self, other). Among your criteria you have self != null, which calls operator !=(self, null)...which checks if self == null, thus calling operator ==(self, null), and round and round you go til you run out of stack space.

I'm pretty sure you can work around this by casting stuff to object for the purposes of reference comparison. Or, you can say Object.ReferenceEquals(self, null) etc, which doesn't rely on == so you don't get the recursion.