In the following C# snippet I override the == method. _type is a number of type short. So I'm actually saying that two WorkUnitTypes are the same when those two shorts are the same.
public static bool operator ==(WorkUnitType type1, WorkUnitType type2)
{
if (type1 == null || type2 == null)
return false;
return type1._type == type2._type;
}
Because R# warns me, and it is totally clear why, that type1/type2 could potentially be null I'm trying to catch that with the if statement above.
Now I'm getting a StackOverflowException which makes totally sense because I'm actually calling the override.
Question: How do I write this method "correct". How can I catch the case that type1 or type2 can be null?
My best guess: Maybe I'm just misusing == here and checking for equality should be done with the Equals override. But still I think the problem exists. So where is my error in reasoning?
You're looking for the ReferenceEquals() function, which will compare directly, bypassing your operator overload.
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