1

Here is my implementation of == and != operators in the class.

 public class MyClass 
    {
        public int         FirstField            { get; set; }
        public int         SecondField            { get; set; }

        public static bool operator ==(MyClass first, MyClass second)
        {
            if (first == null && second == null)
                return true;
            else if (first == null || second == null)
                return false;
            else
            {
                if (first.FirstField == second.FirstField && first.SecondField == second.SecondField)
                    return true;
                else
                    return false;
            }
        }

        public static bool operator !=(MyClass first, MyClass second)
        {
            return !(first == second);
        }
    }

Else where in code I have following two instances that are used for == and != comparisons.

MyClass class1;
MyClass class2;

if (class1 == null || (class1 != null && class1 != class2)  )

Problem is that when line above is called I get a stackoverflow exception at following line.

if (first == null && second == null)

What am I doing wrong here?  
crazy novice
  • 1,757
  • 3
  • 14
  • 36

1 Answers1

3

The first == null in your operator definition re-calls the operator => stack overflow.

What you want to check is for reference equality, which is different from "==" when it is overloaded.

Replace your

        if (first == null && second == null)
            return true;
        else if (first == null || second == null)
            return false;

by

if (ReferenceEquals(first,second))
   return true;
if(ReferenceEquals(first,null) || ReferenceEquals(second,null))
   return false;

side node: your last 'else' body doesnt need a nested 'if'. It can be replaced by return first.FirstField == second.FirstField && first.SecondField == second.SecondField;

Olivier
  • 5,578
  • 2
  • 31
  • 46