C# Language Recursion

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

Note that using recursion can have a severe impact on your code, as each recursive function call will be appended to the stack. If there are too many calls this could lead to a StackOverflowException. Most "natural recursive functions" can be written as a for, while or foreach loop construct, and whilst not looking so posh or clever will be more efficient.

Always think twice and use recursion carefully - know why you use it:

  • recursion should be used when you know the number of recursive calls isn't excessive
    • excessive means, it depends on how much memory is available
  • recursion is used because it is clearer and cleaner code version, it's more readable than an iterative or loop-based function. Often this is the case because it gives cleaner and more compact code (aka less lines of code).
    • but be aware, it can be less efficient! For example in the Fibonacci recursion, to compute the nth number in the sequence, the calculation time will grow exponentially!

If you want more theory, please read:



Got any C# Language Question?