Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Boolean not throw a StackOverflowException?

Tags:

c#

I found Boolean source code on http://referencesource.microsoft.com/#mscorlib/system/boolean.cs:

public struct Boolean
{
    ...
    private bool m_value;
    ...
}

why does it not throw a StackOverflowException?

like image 295
Cologler Avatar asked Sep 03 '15 18:09

Cologler


People also ask

How do I fix exception of type system StackOverflowException was thrown?

StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. So make sure your code doesn't have an infinite loop or infinite recursion.

Can you catch a StackOverflowException C#?

Starting with the . NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow.

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. } } }

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.


1 Answers

The reason why this works is because the bool and System.Boolean types are actually different.

The primitive bool type is a built-in type that stores 1 byte.

The System.Boolean type serves as an object wrapper for the primitive type and implements the IComparable and IConvertable interfaces. This wrapper is implemented to closely represent the primitive type so they may become logically interchangeable.

As .NET Framework users that build on the Common Type System, we simply speak of them as being the same because, in our case, the C# compiler treats the "bool" keyword as an alias for the System.Boolean type that you see implemented in mscorlib.dll.

like image 151
Biscuits Avatar answered Sep 30 '22 00:09

Biscuits