I have a "question" (more a theory then a question which i need to approve) about the following code.
When i start the Program it will cause an Exception: System.StackOverflowException: "Exception_WasThrown".
My theory is now that this exception is gettin' caused, because I'm creating inside the main Method an object of "LOG" and inside of LOG i'm creating an object of FileSize and inside of FileSize i'm creating an object of LOG which also tries to create an object FileSize and this process and its looping.
Is that right or did i misunderstood that, and if yes please explain it to me.
static void Main(string[] args)
{
LOG log = new LOG();
log.getFileSize();
}
}
public class LOG
{
FileSize fileSize = new FileSize();
public void getFileSize()
{
}
}
public class FileSize
{
LOG Log = new LOG();
}
CodePudding user response:
Yes, you're right. Inside the main method you create an instance of the LOG class.The LOG class creates a new instance of the FileSize class ,and the FileSize class creates a new instance of the LOG class.So it's an infinite loop.
CodePudding user response:
Your hunch is correct. What you have programmed there is an infinite recursion.
Of course in reality, this infinite recursion is not really infinite, because of the call stack. Compiler optimizations not withstanding, when a method is invoked a certain amount of memory called a stack frame on this call stack is being allocated, and when that method is returning/exiting, this stack frame is popped from the call stack again. (A stack frame is holding a variety of information pertaining to a particular method call, pertaining to the values passed to and returned from the method, to which code address to return to when the method returns, etc.)
In the case of the "infinite" recursion in your code again, the called methods (like getFileSize() and the LOG constructor) just don't ever return, just calling themselves again and again. And so, more and more stack frames are piled onto the call stack without being ever popped off again (because the recursively called methods never return) until the space in the call stack is exhausted and the StackOverflowException is being thrown in response, and which turns the theoretically infinite recursion into a practically finite recursion with a catastrophic conclusion.