Check null value in override ==

In the next C # snippet, I override the == method. _type is a short number. Therefore, I actually say that two WorkUnitType match if those two short match.

 public static bool operator ==(WorkUnitType type1, WorkUnitType type2) { if (type1 == null || type2 == null) return false; return type1._type == type2._type; } 

Because R # is warning me, and it’s very clear why type1 / type2 might be empty. I am trying to catch this with the if above.

Now I get a StackOverflowException , which makes sense because I am actually calling an override.

Question: How to write this method "correctly." How can I catch the case when type1 or type2 can be null ?

My best guess: Maybe I'm just misusing == here, and equality checking should be done with an override of Equals . But still, I think the problem exists. So where is my mistake in reasoning?

+8
c #
source share
3 answers

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

+9
source share

In addition to what SLaks said, you probably also want to return true if both are zero. So, like this:

 public static bool operator ==(WorkUnitType type1, WorkUnitType type2) { if (ReferenceEquals(type1, null)) return ReferenceEquals(type2, null); if (ReferenceEquals(type2, null)) return false; return type1._type == type2._type; } 
+2
source share

For completeness: you can also pass two arguments to object . This will use the implementation defined in object , not the custom one.

In code:

 if ((object) type1 == null || (object) type2 == null) 
+1
source share

All Articles