Recursion in C#

Our example demonstrates recursive functions in C#. Here’s a classic implementation of factorial calculation using recursion.

using System;

class Recursion
{
    // This Fact method calls itself until it reaches the
    // base case of Fact(0).
    static int Fact(int n)
    {
        if (n == 0)
        {
            return 1;
        }
        return n * Fact(n - 1);
    }

    static void Main()
    {
        Console.WriteLine(Fact(7));

        // In C#, we can define local functions which can be recursive.
        // This is similar to the closure approach in the original example.
        int Fib(int n)
        {
            if (n < 2)
            {
                return n;
            }
            // Since Fib is defined within Main, C# knows which function to call here.
            return Fib(n - 1) + Fib(n - 2);
        }

        Console.WriteLine(Fib(7));
    }
}

To run the program, save it as Recursion.cs and use the C# compiler to build and run it:

$ csc Recursion.cs
$ mono Recursion.exe
5040
13

This example demonstrates two types of recursive functions in C#:

  1. A static method Fact that calculates the factorial of a number.
  2. A local function Fib defined within the Main method that calculates Fibonacci numbers.

The Fact method is a classic example of recursion, where the function calls itself with a smaller argument until it reaches the base case.

The Fib function, defined as a local function within Main, demonstrates how C# allows for recursive local functions. This is conceptually similar to recursive closures in some other languages.

Both functions are called with an argument of 7, and their results are printed to the console.