Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is local function in C#7.0 different from a foreach or a loop?

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.

like image 722
Pradip Avatar asked Nov 16 '17 10:11

Pradip


Video Answer


1 Answers

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.

like image 50
Patrick Hofman Avatar answered Sep 30 '22 04:09

Patrick Hofman