Avoiding Infinite Recursion


It's possible to call procedures in such a way that a continuous loop occurs. Consider the following two procedures:

public static void DoSomething() {     DoSomethingElse(); } public static void DoSomethingElse() {     DoSomething(); }


Calling either of these procedures produces an infinite loop of procedure calls and results in the error shown in Figure 10.11.

Figure 10.11. Infinite recursion results in a stack overflow exception (error).


This endless loop is known as a recursive loop. Without getting too technical, Visual C# allocates some memory for each procedure call in an area known as the stack. Only a finite amount of space is available on the stack, so infinite recursion eventually uses all the available stack space, and an exception occurs. This is a serious error, and steps should be taken to avoid such recursion.

Legitimate uses exist for recursion, most notably in the use of algorithms such as those used in calculus or those used to iterate through all of the folders on a hard drive. Deliberate recursion techniques don't create infinite recursion, however; there is always a point at which the recursion stops (hopefully, before the stack is consumed). If you have an interest in such algorithms, consider reading a book dedicated to the subject.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net