Using Recursion in C#
- Introduction to Programming
- What is C#?
- Your First Console Application in C#
- Introducing Methods and the Main() Function in C#
- Introducing C# Classes and Structs
- C# Data Types, Variables and Casting
- C# Program Flow Control and Entry Points
- Passing Parameters to Methods and Return Values in C#
- C# Access Modifiers and Scope
- C# Interfaces and Classes
- Using Namespaces in C#
- C# Conditional Statements
- Looping and Iteration in C#
- Using Arrays and Lists in C#
- C# Constants and Read-Only Variables
- Error and Exception Handling in C#
- Using Recursion in C#
- C# Operator List
- Class Inheritance in C#
- C# Class and Method Attributes Explained
- C# Class Constructors and Destructors
- C# Generics Variables
- XML Serialization and Deserialization
- C# String Formatting Examples
Recursion is used where a method processes items and calls itself repeatedly to process further items it finds. An example would be a directory tree listing. It first scans the root of the C: drive then calls itself for each directory found. If a subdirectory also contains directories another call to itself is made.
Recursion is also used in mathematics and scientific programming, node programming, artificial intelligence and some database applications.
Recursion is a good way of reusing code and processing multiple levels of data, however, it is very easy for the system to run away. You also need to pass data to the method that can get memory intensive. It will also have an impact on performance.
The following code sample illustrates a recursive method for listing a directory structure.
- using System;
- using System.Threading;
- using System.Text;
- using System.IO;
- class Program
- static void Main()
- StringBuilder dirList = new StringBuilder();
- dirList = directoryListing("c:/Inetpub", "");
- static StringBuilder directoryListing(string path, string indent)
- StringBuilder result = new StringBuilder();
- DirectoryInfo di = new DirectoryInfo(path);
- DirectoryInfo directories = di.GetDirectories();
- foreach (DirectoryInfo dir in directories)
- result.AppendLine(indent + dir.Name);
- // Call the method again on the directories found
- result.Append(directoryListing(dir.FullName, indent + "..").ToString());
- return result;
This routine will scan through the directory specified in the Main method, grab all the sub directories within that directory, add them to the result, and then call itself on each of the subdirectories found. It will recurse until a folder has no subdirectories. Finally, it returns the result back to the line that called the recursive method, until there are no more recursions to be processed. The result is then handed back to the Main method call.
Each time the recursive method is called you need to tell it where to start from, in this case, the folder to look in. In this example, I also use a parameter for the indent level. Each recursion adds two dots to the previous indent level so you can see the directory structure clearer.
It is very easy for a recursive method to run away with itself, an invalid parameter or start point will cause the method to call itself over and over again and never progress. In this case, you will eventually receive a
StackOverflowException, which should be handled with a try catch block on the first call of the method.