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.
Comments
-
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 over 10 yearsThanks 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 over 10 yearsbecause
leftHand == rightHand
called your redefined operator, that in turn calledEquals
, that in turn called your redefined operator and so on. Instead of usingobject.ReferenceEquals
you could have done:((object)leftHand) == ((object)rightHand)
because operators can't bevirtual
, but I think that using theobject.ReferenceEquals
is more clear. Remember if you createstruct
s that you don't need to do this check. Every value ofstruct
type is always distinct, for exampleMyFunc(structValue, structValue)
inMyFunc
you have 2x different copies ofstructValue
. -
Tory over 10 yearsYou 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.