-1

i have created a class that have functionality for the == operator, but i would like to test if the values are null, but when i test for this i start a never ending loop. How can i do the following without creating a never ending loop?

public struct MyClass
{
    private string Value;

    public static bool operator ==(MyClass left, MyClass right)
    {
        if (left == null && right == null)
            return true;
        if (left == null || right == null)
            return false;
        return left.Equals(right);
    }
}
Androme
  • 2,399
  • 4
  • 43
  • 82
  • @JeffMercado the OP is using `==` inside it's very declaration, effectively causing an endless recursion and an eventual `StackOverflowException`. – Federico Berasategui Jun 19 '14 at 23:02
  • 1
    +1 for good question, -1 for overloading `==` for a reference type (which does not seem immutable, see http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx) – vesan Jun 19 '14 at 23:03
  • @vesan Thank you for the tip, i have now made it a struck instead :D – Androme Jun 19 '14 at 23:11

1 Answers1

1

Found the anwser

public struct MyClass
{
    private string Value;

    public static bool operator ==(MyClass left, object right)
    {
        // Test if both are null or the same instance, then return true
        if (ReferenceEquals(left, right))
            return true;

        // If only one of them null return false
        if (((object)left == null) || ((object)right == null))
            return false;

        // Test value
        return left.Equals(right);
    }
}
Androme
  • 2,399
  • 4
  • 43
  • 82