system.stackoverflowexception Cannot evaluate expression because the current thread is in a stack overflow state

13,012

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.

Share:
13,012
Pinu
Author by

Pinu

I am web developer and enjoy writing code!

Updated on June 12, 2022

Comments

  • Pinu
    Pinu almost 2 years

    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));
       }
    
  • Pinu
    Pinu over 10 years
    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.
  • xanatos
    xanatos over 10 years
    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.
  • Tory
    Tory over 10 years
    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.