开发者

Lambda expression syntactic sugar?

开发者 https://www.devze.com 2023-02-16 03:38 出处:网络
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:

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开发者_Go百科 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?


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());


The expression table1.IsChildOf is called a method group.

You are right in that it is equivalent, and indeed this is syntactic sugar.


It's called a method group. Resharper encourages this kind of code.

0

精彩评论

暂无评论...
验证码 换一张
取 消