In this article, we are going to talk about Recursion and Recursive Methods in C#. Furthermore, we will learn how to use recursive methods and how they differ from regular methods.

For the complete navigation of this series check out: C# Back to Basics.

If you want to download the source code for our examples, you can do that from here Recursive Methods in C# Source Code.

So what is recursion?

Recursion is a concept in which method calls itself. Every recursive method needs to be terminated, therefore, we need to write a condition in which we check is the termination condition satisfied. If we don’t do that, a recursive method will end up calling itself endlessly.

Example 1: Create an application which calculates the sum of all the numbers from n to m recursively:

Recursion and Recursive Methods

Code Explanation

The method CalculateSumRecursively is our recursive method that calculates the sum of the numbers from n to m. The first thing we do is to set our sum to the value of n. Then, we check if the value of n is less than the value of m. If it is, we increase the value of n by 1 and add to our sum a result of the same method but with the increased n. If it is not, we just return the value of the sum variable.

The C# will reserve memory storage for every recursive method so that the values from the previous method are not overridden.

So let’s see our example through the diagram:

Graph Recursion and Recursive Methods

Additional Example

Let’s practice some more with the Example2: Create an application which prints out how many times the number can be divided by 2 evenly:



Now we have a good knowledge of recursion and recursive methods.

In the next post, we are going to talk about Arrays in C#, how to use them and about different types of arrays.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.