Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of C# 7 local functions over lambdas? [duplicate]

The other day in one of my utilities, ReSharper hinted me about the piece of code below stating that lambda defining the delegate ThreadStart can be turned into a local function:

public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest)
{
    if (!Enabled)
    {
        _threadCancellationRequested = false;

        ThreadStart threadStart = () => NotificationTimer (ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested);

        Thread = new Thread(threadStart) {Priority = ThreadPriority.Lowest};
        Thread.Start();
    }
}

And hence transformed into:

public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest)
{
    if (!Enabled)
    {
        _threadCancellationRequested = false;

        void ThreadStart() => NotificationTimer(ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested);

        Thread = new Thread(ThreadStart) {Priority = ThreadPriority.Lowest};
        Thread.Start();
    }
}

What are the benefits of the latter over the former, is it only about performance?

I've already checked the resources below but in my example the benefits are not that obvious:

  • https://asizikov.github.io/2016/04/15/thoughts-on-local-functions/
  • https://www.infoworld.com/article/3182416/application-development/c-7-in-depth-exploring-local-functions.html
like image 392
Natalie Perret Avatar asked Oct 09 '17 22:10

Natalie Perret


People also ask

Why is C language powerful?

C is one of the most powerful "modern" programming language, in that it allows direct access to memory and many "low level" computer operations. C source code is compiled into stand-a-lone executable programs.

Is there any benefit in learning C?

Being a middle-level language, C reduces the gap between the low-level and high-level languages. It can be used for writing operating systems as well as doing application level programming. Helps to understand the fundamentals of Computer Theories.


1 Answers

The 1st website you linked mentions some benefits of local functions:
- A lambda causes allocation.
- There's no elegant way of writing a recursive lambda.
- They can't use yield return and probably some other things.

One useful use-case is iterators:

Wrong way:

public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) {
    //Since this method uses deferred execution,
    //this exception will not be thrown until enumeration starts.
    if (source == null)
        throw new ArgumentNullException();
    yield return something;
}

Right way:

public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) {
    if (source == null)
        throw new ArgumentNullException();
    return Iterator();

    IEnumerable<T> Iterator() {
        yield return something;
    }
}
like image 184
Dennis_E Avatar answered Oct 12 '22 07:10

Dennis_E