What is the meaning of this expression " () =>". I have seen it used in a constructor:
return new MyItem(itemId, () => MyFunction(myParam));
Thank you
What is the meaning of this expression " () =>". I have seen it used in a constructor:
return new MyItem(itemId, () => MyFunction(myParam));
Thank you
It's a delegate without parameters, written as a lambda. Same as:
return new MyItem(itemId, delegate() {return MyFunction(myParam); });
That is a lambda expression. The code in your example is equivalent to this:
return new MyItem(itemId, delegate() { MyFunction(myParam); });
It is a lambda expression, which is roughly equivalent to an anonymous delegate, although much more powerful
ya this is a lambda expression. The compiler automatically create delegates or expression tree types
Here's the simple examples of lambda I just created:
internal class Program
{
private static void Main(string[] args)
{
var item = new MyItem("Test");
Console.WriteLine(item.Text);
item.ChangeText(arg => MyFunc(item.Text));
Console.WriteLine(item.Text);
}
private static string MyFunc(string text)
{
return text.ToUpper();
}
}
internal class MyItem
{
public string Text { get; private set; }
public MyItem(string text)
{
Text = text;
}
public void ChangeText(Func<string, string> func)
{
Text = func(Text);
}
}
The output will be:
Test
TEST
A lot of people have replied that this is just an anonymous function. But that really depends on how MyItem is declared. If it is declared like this
MyItem(int itemId, Action action)
Then yes, the () => {} will be compiled to an anonymous function. But if MyItem is declared like this:
MyItem(int itemId, Expression<Action> expression)
Then the () => {} will be compiled into an expression tree, i.e. MyItem constructor will receive an object structure that it can use to examine what the actual code inside the () => {} block was. Linq relies heavily on this for example in Linq2Sql where the LinqProvider examines the expression tree to figure out how to build an SQL query based on an expression.
But in most cases () => {} will be compiled into an anonymous function.