Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression syntactic sugar?

I have just come across the following code (.NET 3.5), which doesn't look like it should compile to me, but it does, and works fine:

bool b = selectedTables.Any(table1.IsChildOf));

Table.IsChildOf is actually a method with following signature:

public bool IsChildOf(Table otherTable)

Am I right in thinking this is equivalent to:

bool b = selectedTables.Any(a => table1.IsChildOf(a));

and if so, what is the proper term for this?

like image 747
tomfanning Avatar asked Mar 10 '11 10:03

tomfanning


People also ask

What is the syntax of defining lambda expression?

A lambda expression is an anonymous function that provides a concise and functional syntax, which is used to write anonymous methods. It is based on the function programming concept and used to create delegates or expression tree types. The syntax is function(arg1, arg2... argn) expression.

What is a lambda expression example?

Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces.

What kind of variable you can access in an lambda expression?

A lambda expression can access a variable of it's enclosing scope. A Lambda expression has access to both instance and static variables of it's enclosing class and also it can access local variables which are effectively final or final.

Can we use lambda without functional interface?

You do not have to create a functional interface in order to create lambda function.


1 Answers

This is a method group conversion, and it's been available since C# 2. As a simpler example, consider:

public void Foo()
{
}

...

ThreadStart x = Foo;
ThreadStart y = new ThreadStart(Foo); // Equivalent code

Note that this is not quite the same as the lambda expression version, which will capture the variable table1, and generate a new class with a method in which just calls IsChildOf. For Any that isn't important, but the difference would be important for Where:

var usingMethodGroup = selectedTables.Where(table1.IsChildOf);
var usingLambda = selectedTables.Where(x => table1.IsChildOf(x));
table1 = null;

// Fine: the *value* of `table1` was used to create the delegate
Console.WriteLine(usingMethodGroup.Count());

// Bang! The lambda expression will try to call IsChildOf on a null reference
Console.WriteLine(usingLambda.Count());
like image 187
Jon Skeet Avatar answered Sep 30 '22 18:09

Jon Skeet