Recursion is a technique used in computer science to define a problem in terms of the problem itself, usually in terms of a simpler version of the problem itself.
For example, the implementation of the generator for the n-th value of the Fibonacci sequence comes naturally from its mathematical definition, when recursion is used:
Use of recursion is acceptable in methods, like the one above, where you can break out of it.
[source,csharp]
----
int NthFibonacciNumber(int n)
{
if (n <= 1)
{
return 1; // Base case: stop the recursion
}
// ...
}
----
It is also acceptable and makes sense in some type definitions:
[source,csharp]
----
class Box : IComparable<Box>
{
public int CompareTo(Box? other)
{
// Compare the two Box instances...
}
}
----
With types, some invalid recursive definitions are caught by the compiler:
[source,csharp]
----
class C2<T> : C2<T> // Error CS0146: Circular base type dependency
{
}
class C2<T> : C2<C2<T>> // Error CS0146: Circular base type dependency
{
}
----
In more complex scenarios, however, the code will compile but execution will result into a https://learn.microsoft.com/en-us/dotnet/api/system.typeloadexception[TypeLoadException] if you try to instantiate the class.