Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for null in == override

Tags:

c#

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?

like image 420
Stephan Avatar asked May 13 '15 19:05

Stephan


1 Answers

You're looking for the ReferenceEquals() function, which will compare directly, bypassing your operator overload.

like image 88
SLaks Avatar answered Sep 20 '22 07:09

SLaks