Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does String.Equals(a,b) not produce a StackOverflowException?

Tags:

c#

.net

People also ask

What causes StackOverflowException?

A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }

Can you catch a StackOverflowException?

NET Framework 2.0, you can't catch a StackOverflowException object with a try / catch block, and the corresponding process is terminated by default. Consequently, you should write your code to detect and prevent a stack overflow.

What causes stack overflow c#?

The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack. An example of infinite recursion in C.

How to fix stack overflow error in c#?

Solution 1Your get method is referencing the property name and not the private variable name. This means when you get the value of val , your code goes into a never ending loop as the result references itself. In . Net this will eventually cause a stack overflow exception.


Your decompiler has a bug. The real code doesn't check a == b, it checks (Object)a == (Object)b, bypassing the overloaded operator.


Here is the real code from Microsoft. Operator == is implemented as

public static bool operator == (String a, String b) {
   return String.Equals(a, b);
}

operator == calls String.Equals which is implemented as:

public static bool Equals(String a, String b) {
    if ((Object)a==(Object)b) {
        return true;
    }

    if ((Object)a==null || (Object)b==null) {
        return false;
    }

    if (a.Length != b.Length)
        return false;

    return EqualsHelper(a, b);
}

As you see, the comparison for string equality is done using if ((Object)a==(Object)b) casting the string to object and then doing the comparison. So this will not call the overloaded operator == in string class.