This is more of a why question. Here it goes.
C# 7.0 added a new feature called "Local Function". Below is a code snippet.
public int Fibonacci(int x)
{
if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));
return Fib(x).current;
(int current, int previous) Fib(int i)
{
if (i == 0) return (1, 0);
var (p, pp) = Fib(i - 1);
return (p + pp, p);
}
}
What I dont understand is, its doing a recursive call to the same method. We can easily achieve this with a normal foreach. Then why a local function.
MSDN says
methods implemented as iterators commonly need a non-iterator wrapper method for eagerly checking the arguments at the time of the call. (The iterator itself doesn’t start running until MoveNext is called).
Need some help in understanding the concept that it.
its doing a recursive call to the same method. We can easily achieve this with a normal foreach
That are two different things: tail recursion (method calling itself at the end of the method itself) or iterating over a collection. They are not always exchangeable, but they can be used to achieve the same end result.
The local function is nothing more that a class method, with a scope limited to the method body it is declared in.
Local functions are useful for many more than recursion. It is an easy way to prevent repeating code in several blocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With