Lambda expression syntactic sugar?

I just stumbled upon the following code (.NET 3.5), which doesn't look like it should compile for me, but it works and works fine:

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

Table.IsChildOf is actually a method with the following signature:

public bool IsChildOf(Table otherTable)

I think this is equivalent to:

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

and if so, what is the right term for?

+5
source share
3 answers

This is a transformation of a group of methods, and it is available with C # 2. As a simpler example, consider:

public void Foo()
{
}

...

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

, , -, table1 , IsChildOf. Any , 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());
+13

table1.IsChildOf .

, , , .

+5

It is called a group of methods. Resharper encourages this type of code.

+2
source

All Articles