C# · Chapter 28 of 46

C# Recursion

Recursion is when a method calls itself to solve a smaller version of the same problem. Every recursive method needs a base case — a condition that stops the recursion — to avoid infinite calls.

Recursion is often used for problems that have a naturally recursive structure, like calculating factorials, traversing trees, or computing Fibonacci numbers.

Syntax
static int Method(int n) {
  if (n == baseCase) return baseValue;
  return Method(n - 1);
}

Base case and recursive case

The base case is the simplest scenario that returns a result directly without further recursion. The recursive case breaks the problem down and calls the method again with a smaller input.

Stack considerations

Each recursive call adds a new frame to the call stack. Too many recursive calls without reaching a base case causes a StackOverflowException.

Example 1 (csharp)
using System;

class Program {
  static int Factorial(int n) {
    if (n == 0) return 1;
    return n * Factorial(n - 1);
  }

  static void Main() {
    Console.WriteLine(Factorial(5));
  }
}
Output
120

Factorial(5) calls Factorial(4), Factorial(3), and so on until the base case n == 0 is reached.

Example 2 (csharp)
using System;

class Program {
  static int Fibonacci(int n) {
    if (n <= 1) return n;
    return Fibonacci(n - 1) + Fibonacci(n - 2);
  }

  static void Main() {
    Console.WriteLine(Fibonacci(6));
  }
}
Output
8

Fibonacci(6) recursively sums the two preceding Fibonacci numbers until reaching the base case.

Key points

  • Recursion is when a method calls itself.
  • Every recursive method needs a base case to stop the recursion.
  • Recursion can be a clean way to solve naturally recursive problems.
  • Excessive recursion depth can cause a StackOverflowException.
💡 Note: Some recursive problems, like Fibonacci, can be solved more efficiently with loops or memoization to avoid repeated work.

📝 Quick Quiz

1. What is a base case in recursion?

2. What happens without a base case?

3. What does Factorial(0) return in the example?