3

I am getting a System.StackOverFlowException when the code hits this function.

Where stringtype is user defined tupe and equals int the function in the type library.

  public static bool Equals(StringType leftHand, StringType rightHand)
  {
       if (leftHand == rightHand)
       {
          return true;
       }
       if ((leftHand == "0") || (rightHand == "0"))
       {
          return false;
       }
       return (leftHand.myValue.Equals(rightHand.myValue) && leftHand.myState.Equals(rightHand.myState));
   }
1
  • 1
    It's better if you tell us the overridden operators of your StringType class
    – xanatos
    Commented Aug 12, 2013 at 14:13

1 Answer 1

10

This

if (leftHand == rightHand)

change to

if (object.ReferenceEquals(leftHand, rightHand))

You probably redefined the == operator to call Equals.

And I hope you don't have an implicit operator that from string creates StringType, because otherwise

if ((leftHand == "0") || (rightHand == "0"))

will probably call itself for the same reason.

Probably

if ((leftHand.myValue == "0") || (rightHand.myValue == "0"))

would be better.

3
  • Thanks xanatos , When I changed the code it ran without error. What you guess is right that we redefined the == operator. I am just curious to know what why it was giving an error when lefthand == right hand.
    – Pinu
    Commented Aug 12, 2013 at 14:32
  • 1
    because leftHand == rightHand called your redefined operator, that in turn called Equals, that in turn called your redefined operator and so on. Instead of using object.ReferenceEquals you could have done: ((object)leftHand) == ((object)rightHand) because operators can't be virtual, but I think that using the object.ReferenceEquals is more clear. Remember if you create structs that you don't need to do this check. Every value of struct type is always distinct, for example MyFunc(structValue, structValue) in MyFunc you have 2x different copies of structValue.
    – xanatos
    Commented Aug 12, 2013 at 14:34
  • You were making the class recursive with no way out. .Equals(StringType, StringType) would immediately call ==(StringType) which would then immediately call .Equals(StringType, StringType), et cetera ad absurdum until the call stack ran out of room and threw a StackOverflowException.
    – Tory
    Commented Aug 12, 2013 at 14:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.