Local function vs Lambda C# 7.0

I am looking at the new implementations in C# 7.0 and I find it interesting that they have implemented local functions but I cannot imagine a scenario where a local function would be preferred over a lambda expression, and what is the difference between the two.

I do understand that lambdas are anonymous functions meanwhile local functions are not, but I can't figure out a real world scenario, where local function has advantages over lambda expressions

Any example would be much appreciated. Thanks.

This was explained by Mads Torgersen in C# Design Meeting Notes where local functions were first discussed:

You want a helper function. You are only using it from within a single function, and it likely uses variables and type parameters that are in scope in that containing function. On the other hand, unlike a lambda you don't need it as a first class object, so you don't care to give it a delegate type and allocate an actual delegate object. Also you may want it to be recursive or generic, or to implement it as an iterator.

To expand on it some more, the advantages are:

  1. Performance.

    When creating a lambda, a delegate has to be created, which is an unnecessary allocation in this case. Local functions are really just functions, no delegates are necessary.

    Also, local functions are more efficient with capturing local variables: lambdas usually capture variables into a class, while local functions can use a struct (passed using ref), which again avoids an allocation.

    This also means calling local functions is cheaper and they can be inlined, possibly increasing performance even further.

  2. Local functions can be recursive.

    Lambdas can be recursive too, but it requires awkward code, where you first assign null to a delegate variable and then the lambda. Local functions can naturally be recursive (including mutually recursive).

  3. Local functions can be generic.

    Lambdas cannot be generic, since they have to be assigned to a variable with a concrete type (that type can use generic variables from the outer scope, but that's not the same thing).

  4. Local functions can be implemented as an iterator.

    Lambdas cannot use the yield return (and yield break) keyword to implement IEnumerable<T>-returning function. Local functions can.

  5. Local functions look better.

    This is not mentioned in the above quote and might be just my personal bias, but I think that normal function syntax looks better than assigning a lambda to a delegate variable. Local functions are also more succinct.

    Compare:

    int add(int x, int y) => x + y;
    Func<int, int, int> add = (x, y) => x + y;
    

Local function vs Lambda C# 7.0, C# Local Functions vs. Lambda Expressions. 7 minute read. C# Local Functions are often viewed as a further enhancement of lambda� Both local functions and lambda expression rules demand that any captured variables are definitely assigned at the point when the local function or lambda expression is converted to a delegate. The difference is that lambda expressions are converted to delegates when they are declared. Local functions are converted to delegates only when used as a delegate.

In addition to svick's great answer there is one more advantage to local functions: They can be defined anywhere in the function, even after the return statement.

public double DoMath(double a, double b)
{
    var resultA = f(a);
    var resultB = f(b);
    return resultA + resultB;

    double f(double x) => 5 * x + 3;
}

C# Local Functions vs. Lambda Expressions., But with release of C# 7 local functions got introduced. It has some similarity to lambdas but also some major differences. Local functions are� Local functions can naturally be recursive (including mutually recursive). Local functions can be generic. Lambdas cannot be generic, since they have to be assigned to a variable with a concrete type (that type can use generic variables from the outer scope, but that's not the same thing).

If you also wonder how to test local function you should check JustMock as it has the functionality to do it. Here is a simple class example that will be tested:

public class Foo // the class under test
{ 
    public int GetResult() 
    { 
        return 100 + GetLocal(); 
        int GetLocal () 
        { 
            return 42; 
        } 
    } 
}

And here is how the test looks:

[TestClass] 
public class MockLocalFunctions 
{ 
    [TestMethod] 
    public void BasicUsage() 
    { 
        //Arrange 
        var foo = Mock.Create<Foo>(Behavior.CallOriginal); 
        Mock.Local.Function.Arrange<int>(foo, "GetResult", "GetLocal").DoNothing(); 

        //Act 
        var result = foo. GetResult(); 

        //Assert 
        Assert.AreEqual(100, result); 
    } 
} 

Here is a link to JustMock documentation.

Disclaimer. I am one of the developers responsible for JustMock.

Lambdas vs Local Functions What's the Difference, Frankly when I first saw that C# 7 will come with new local functions I thought that that's There is no elegant way to define recursive lambda:. C# Local Functions vs. Lambda Expressions. 7 minute read C# Local Functions are often viewed as a further enhancement of lambda expressions. While the features are related, there are also major differences. Local Functions is the C# implementation of Nested function feature. It is a bit unusual for a language to get support for nested functions several versions after supporting lambdas.

I use inline functions to avoid garbage collection pressure specially when dealing with longer running methods. Say one would like to get 2 years or market data for a given ticker symbol. Also, one can pack a lot of functionality and business logic if one needs to.

what one does is open a socket connection to the server and loop over the data binding an event to a event. One can think of it the same way as a class is designed, only one is not writing helper methods all over the place that are really only working for one pice of functionality. below is some sample of how this might look like, please note that i am using variables and the "helper" methods are below the finally. In the Finally I nicely remove the event handlers, if my Exchange class would be external/injected i would not have any pending event handler registrated

void List<HistoricalData> RequestData(Ticker ticker, TimeSpan timeout)
{
    var socket= new Exchange(ticker);
    bool done=false;
    socket.OnData += _onData;
    socket.OnDone += _onDone;
    var request= NextRequestNr();
    var result = new List<HistoricalData>();
    var start= DateTime.Now;
    socket.RequestHistoricalData(requestId:request:days:1);
    try
    {
      while(!done)
      {   //stop when take to long….
        if((DateTime.Now-start)>timeout)
           break;
      }
      return result;

    }finally
    {
        socket.OnData-=_onData;
        socket.OnDone-= _onDone;
    }


   void _OnData(object sender, HistoricalData data)
   {
       _result.Add(data);
   }
   void _onDone(object sender, EndEventArgs args)
   {
      if(args.ReqId==request )
         done=true;
   } 
}

You can see the advantages as mentioned below, here you can see a sample implementation. Hope that helps explaining the benefits.

Thoughts on C# 7 Local Functions, A great feature of C# 7.0 are local functions. Local functions have the syntax of methods and can be used within the scope of methods,� For more information, see Local functions vs. lambda expressions. More expression-bodied members C# 6 introduced expression-bodied members for member functions, and read-only properties.

Local Functions – What's the Value? – csharp.christiannagel.com, I am looking at the new implementations in C# 7.0 and I find it interesting that they have implemented local functions but I cannot imagine a scenario where a� This article introduces how to use Func, Action and Local Function in C# 7 language. These methods are used to hide a method in another method or nested method. Func and Action are predefined generic delegates, which take zero to sixteen input parameters.

Local function vs Lambda C# 7.0, You can say that Lambdas may be the most significant improvement in any new version of C#. Local Functions were introduced with C# 7.0 and� Thoughts on C# 7 Local Functions 15 Apr 2016. Frankly when I first saw that C# 7 will come with new local functions I thought that that’s just a nice and a compact way of defining local helpers. In fact, it’s much more interesting and useful feature. Today I’m going to talk about it in more details.

Why I Fell in Love With Local Functions in C#!, Func delegate type can be used with an anonymous method or lambda expression. Here, we create an example, which checks whether a� This is how a local function is declared in C# 7.0. It works the same way as a lambda but without allocation and without exposing private functions that shouldn’t be exposed.

Comments
  • Generics, out parameters, recursive functions without having to initialize the lambda to null, etc.
  • @KirkWoll - You should post this as an answer.
  • I would like to add that local functions have parameter names on the caller side. Lambdas don't.
  • @Lensflare It's true that parameter names of lambdas are not preserved, but that's because they have to be converted to delegates, which have their own names. For example: Func<int, int, int> f = (x, y) => x + y; f(arg1:1, arg2:1);.
  • Great list! However, I can imagine how the IL/JIT compiler could perform all optimizations mentioned in 1. also for delegates if their usage adheres to certain rules.
  • @Casebash Because lambdas always use a delegate and that delegate holds the closure as an object. So, lambdas could use a struct, but it would have to be boxed, so you would still have that additional allocation.
  • @happybits Mostly when you don't need to give a name to it, like when you're passing it to method.
  • This is really useful, as I can getting used to putting all the helper functions in a #region Helpers at the bottom of the function, so to avoid clutter within that function and espically avoid clutter in the main class.
  • I also appreciate this. It makes the main function that you're looking at easier to read, as you don't need to look around to find where it starts. If you want to see the implementation details, keep looking past the end.
  • if your functions are so big they need regions in them, they're too big.
  • it's great seeing such passionate developers advocating for people to use their tool. How did you get interested in writing developer tools as a full time job? As an American, my impression is that it can be hard to find such careers unless you have a masters or Ph.D. in comp sci.
  • Hi John and thank you for the kind words. As a software developer, I don't see anything better than being appreciated by my clients for the value I provide for them. Combine that with the desire for challenging and competitive work and you will receive a fairly limited list of things I would be passioned about. Writing productivity developer tooling is on that list. At least in my mind :) Regarding the career, I think that the companies providing developer tooling are quite a small percentage of all software companies and this is why it is harder to find such an opportunity.
  • One separate question. Why don't you call VerifyAll here? Is there a way to tell JustMock to verify the local function was called, too?