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
- public void NameOfRecursiveMethod(string directoryToSearch)
- {
- // Go in deep as far as possible, then work backwards.
- // Find all the subdirectories under this directory.
- foreach (string dir in Directory.GetDirectories(directoryToSearch))
- {
- // Recursive call for each subdirectory.
- this.NameOfRecursiveMethod(dir);
- }
- // Note: The First time we arrive here will be inside the deepest first directory
- // Get all files in the directory
- string[] files = Directory.GetFiles(directoryToSearch);
- foreach (string filename in files)
- {
- // Do something for each file here
- }
- }
End of Code Snippet
No comments:
Post a Comment