Recursion


Calling a method recursively or implementing the method using recursion refers to the fact that the method calls back on itself. This is sometimes the simplest way to implement a method. Listing 4.15 counts the lines of all the C# source files (*.cs) in a directory and its subdirectory.

Listing 4.15. Returning All the Filenames, Given a Directory

 using System.IO; public static class LineCounter {   // Use the first argument as the directory   // to search, or default to the current directory. public static void Main(string[] args) {     int totalLineCount = 0;     string directory;     if (args.Length > 0)     {         directory = args[0];     }     else     {         directory = Directory.GetCurrentDirectory();     }     totalLineCount = DirectoryCountLines(directory);     System.Console.WriteLine(totalLineCount);   } static int DirectoryCountLines(string directory)                 {     int lineCount = 0;     foreach (string file in         Directory.GetFiles(directory, "*.cs"))     {           lineCount += CountLines(file);       }          foreach (string subdirectory in         Directory.GetDirectories(directory))     {         lineCount += DirectoryCountLines(subdirectory);             }       return lineCount;  }    private static int CountLines(string file)  {      string line;      int lineCount = 0;      FileStream stream =          new FileStream(file, FileMode.Open);      StreamReader reader = new StreamReader(stream);      line = reader.ReadLine();         while(line != null)       {          if (line.Trim() != "")          {              lineCount++;          }          line = reader.ReadLine();          }         reader.Close();         stream.Close();         return lineCount;     } } 

Output 4.9 shows the results of Listing 4.15.

Output 4.9.

 104 

The program begins by passing the first command-line argument to DirectoryCountLines(), or by using the current directory if no argument was provided. This method first iterates through all the files in the current directory and totals the source code lines for each file. After each file in the directory, the code processes each subdirectory by passing the subdirectory back into the DirectoryCountLines() method, rerunning the method using the subdirectory. The same process is repeated recursively through each subdirectory until no more directories remain to process.

Readers unfamiliar with recursion may find it cumbersome at first. Regardless, it is often the simplest pattern to code, especially with hierarchical type data such as the filesystem. However, although it may be the most readable, it is generally not the fastest implementation. If performance becomes an issue, then developers should seek an alternate solution in place of a recursive implementation. The choice generally hinges on balancing readability with performance.

Beginner Topic: Infinite Recursion Error

A common programming error in recursive method implementations appears in the form of a stack overflow during program execution. This usually happens because of infinite recursion, in which the method continually calls back on itself, never reaching a point that indicates the end of the recursion. It is a good practice for programmers to review any method that uses recursion and verify that the recursion calls are finite.





Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

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