views:

172

answers:

7

What is the meaning of this expression " () =>". I have seen it used in a constructor:

return new MyItem(itemId, () => MyFunction(myParam));

Thank you

+8  A: 

It's a delegate without parameters, written as a lambda. Same as:

return new MyItem(itemId, delegate() {return MyFunction(myParam); });
Philippe Leybaert
Mean delegate() { return MyFunction(myParam); }!
Dario
yes, of course. Slight oversight (I fixed it in my answer)
Philippe Leybaert
+1  A: 

It's the lambda expression.

RaYell
+6  A: 

That is a lambda expression. The code in your example is equivalent to this:

return new MyItem(itemId, delegate() { MyFunction(myParam); });
bobbymcr
+1  A: 

It is a lambda expression, which is roughly equivalent to an anonymous delegate, although much more powerful

Thomas Levesque
+1  A: 

ya this is a lambda expression. The compiler automatically create delegates or expression tree types

anishmarokey
+1  A: 

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

Vadim
+2  A: 

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.

Pete