Friday 6 February 2015

Recursion and Recursive Methods for Dummies - Working C# Example


In Brief
What is Recursion: Very simply put... A method that calls itself.
Why use Recursion?: So we can repeat a methods logic any number of times with differing arguments.
What is an Example of Recursion?: Directories which contain directories which contain more directories and you would like to scan through all of the files within this directory chain. We can create ONE SINGLE method to do this by calling itself recursively. See below for full example.

Here is a working example of a recursive method in C#. It takes a file directory as an argument and recursively loops through all of the files which the WHOLE directory structure. It goes in deep, then works backwards. This is an example of backwards or tail recursion.

Code Snippet
  1. public void NameOfRecursiveMethod(string directoryToSearch)
  2. {
  3.     // Go in deep as far as possible, then work backwards.
  4.     // Find all the subdirectories under this directory.
  5.     foreach (string dir in Directory.GetDirectories(directoryToSearch))
  6.     {
  7.         // Recursive call for each subdirectory.
  8.         this.NameOfRecursiveMethod(dir);
  9.     }
  10.    
  11.     // Note: The First time we arrive here will be inside the deepest first directory
  12.     // Get all files in the directory
  13.     string[] files = Directory.GetFiles(directoryToSearch);
  14.  
  15.     foreach (string filename in files)
  16.     {
  17.         // Do something for each file here
  18.        
  19.     }
  20. }
End of Code Snippet

No comments: