I recently came to a situation where operator overloading C# (specifically the == operator) would really be beneficial. Since I’ve typically steered away from this technique, for readability and maintainability, I hadn’t had much experience with it.
My overloaded operator looks something like this:
static bool operator==(Id<T> a, Id<T> b)
{
return a.Value == b.Value;
}
That has been working just as planned for a few months now, but today I hit a snag when trying to do a null test against a variable of that class type, like:
Id<int> x;
...
if (x == null)
{
...
}
This causes a nice null reference exception at a.Value
because a is null. My first thought was to test for null in the operator== method before I attempt accessing a.Value (or b.Value), like:
if (a == null)
{
return b == null;
}
else
{
return a.Value == b.Value;
}
Thinking I had the problem fixed, I reran; and quickly hit a StackOverFlowException. What the? Ooooh, the if (a == null)
was causing that method to be called over and over, recursively until it blew the stack! OK, now how the heck can I test against null without the operator== being called??
After a moment of slight panic, I realized how to get around it. When doing just if (a == null)
, the Id class’ static overload is being called. The way out of this is to have the object
class’ operator==
explicitly called by making a simple change:
if ((object)a == null)
{
return ((object)b == null);
}
else
{
return a.Value == b.Value;
}
And that’s it! I now have an overload that handles null checking.
Comments
4 responses to “C# operator== overloading”
Does this logic fail if “a” isn’t null?
a = new Id();
b = null;
if (a == null) { …
-David
LikeLike
Yep, good catch 🙂
LikeLike
I was gonna say that too, but he beat me to it. Damn.
LikeLike
Darn! Gotta be quicker!
LikeLike