Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures and Lambda in C#

I get the basic principles of closures and lambda expressions but I'm trying to wrap my mind around what is happening behind the scenes and when it is/isn't practical to use them in my code. Consider the following example, that takes a collection of names and returns any names that begin with the letter C...

    static void Main(string[] args)
    {
        List<string> names = new List<string>();
        names.AddRange(new string[]
        {
            "Alan", "Bob", "Chris", "Dave", "Edgar", "Frank"
        });


        names.FindAll(x => x.StartsWith("C")).ForEach(
            i => Console.WriteLine(i));

    }

First, is there a more direct way that I could have written this expression? Secondly, isn't "FindAll" going to allocate memory for a new collection that holds the matching items? I definitely see that the syntax is more elegant, but I want to make sure I'm not walking into performance issues later down the road when working with larger collections. Does the compiler do some optimization voodoo behind the scenes that makes my concerns invalid?

like image 965
lJohnson Avatar asked Aug 20 '09 15:08

lJohnson


People also ask

What are lambdas and closures?

A lambda expression is an anonymous function and can be defined as a parameter. The Closures are like code fragments or code blocks that can be used without being a method or a class. It means that Closures can access variables not defined in its parameter list and also assign it to a variable.

Is there lambda function in C?

Significance of Lambda Function in C/C++ Lambda Function − Lambda are functions is an inline function that doesn't require any implementation outside the scope of the main program. Lambda Functions can also be used as a value by the variable to store.

Why a lambda expression forms a closure?

To prevent invalid references, the compiler creates what's called a closure for the Lambda expression. A closure is a wrapper class that contains the Lambda expression and fields that contain copies of the local variables. Since the closure is an object created with new, it's not cleaned up when the scope exits.

What is the lambda keyword used for what is a closure?

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.


1 Answers

Yes, FindAll will create a new list. You want "Where", which will return an IEnumerable object that knows how to loop over your existing list:

foreach (string name in names.Where(n => n.StartsWith("C") ) ) 
{
    Console.WriteLine(name);
}

But there's no closure in that code, because there's no local variable to capture.

like image 52
Joel Coehoorn Avatar answered Oct 15 '22 23:10

Joel Coehoorn