Web Design that taps into the haromny and vision of your dreams.

Using Recursion in C#

Shooting yourself in the foot, over and over again

Written By on in C#

407 words, estimated reading time 2 minutes.

Recursion is the process whereby a method calls itself until an exit condition is met. Very useful, but also very easy to shoot yourself in the foot over and over and over again.

C# Programming Series
  1. Introduction to Programming
  2. What is C#?
  3. Your First Console Application in C#
  4. Introducing Methods and the Main() Function in C#
  5. Introducing C# Classes and Structs
  6. C# Data Types, Variables and Casting
  7. C# Program Flow Control and Entry Points
  8. Passing Parameters to Methods and Return Values in C#
  9. C# Access Modifiers and Scope
  10. C# Interfaces and Classes
  11. Using Namespaces in C#
  12. C# Conditional Statements
  13. Looping and Iteration in C#
  14. Using Arrays and Lists in C#
  15. C# Constants and Read-Only Variables
  16. Error and Exception Handling in C#
  17. Using Recursion in C#
  18. C# Operator List
  19. Class Inheritance in C#
  20. C# Class and Method Attributes Explained
  21. C# Class Constructors and Destructors
  22. C# Generics Variables
  23. XML Serialization and Deserialization
  24. 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.

Last updated on: Friday 23rd June 2017


Gisle Aune

Gisle Aune

Isn't a for loop more effective when adressing each object in a collection? Like this?

DirectoryInfo dir = null;
for(int i = 0; int i < directories.length; i += 1)
dir = directories[i]
result.AppendLine(indent + dir.Name);

// Call the method again on the directories found
result.Append(directoryListing(dir.FullName, indent + "..").ToString());


Reply to Gisle Aune
Tim Trott

Tim Trott

Yes, you are absolutely correct. Performance wise a for loop is much faster to execute and should be used for performance critical applications. It wasn't until I did some investigation that I found out just how much faster a for loop was. Time to rethink my foreach use!


Reply to Tim Trott


Leave a Reply

Your email address will not be published.

If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me