What is Recursion?
Recursion is a term that is used to describe a function that calls itself.
In the example below I have an Box
object which has Content and possibly another Box inside. Now I want to be able to get all of the contents of the Box
and any Box
that it contains, and so on and so on.
A way we can achieve this is recursion. We have a method of GetBoxContents
which takes in a Box
and returns a string
for the contents of the box. In this method it retrieves the Content of the Box and then if it has an InnerBox
it will
call GetBoxContents
again to get the Content
of the InnerBox
and anything that may contain.
class Box{
string Content { get; set; }
Box InnerBox { get; set; }
}
string GetBoxContents(Box box){
var contents = box.Content;
if(box.InnerBox != null){
contents = contents + GetBoxContents(box.InnerBox);
}
return contents;
}
This is a recursive method. I have found recursive methods to be very useful in some use cases such as when I needed to traverse a string of json and map json objects to C# objects through a nested json structure.
Recursion is not always going to be a solution for the problem you have, but It can be really helpful at simplifying a complex issue.