Gregoire
Gregoire

Reputation: 24872

c# 3.0 Meaning of expression ()=>

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

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

Thank you

Upvotes: 3

Views: 353

Answers (7)

Philippe Leybaert
Philippe Leybaert

Reputation: 171904

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

return new MyItem(itemId, delegate() {return MyFunction(myParam); });

Upvotes: 8

Pete
Pete

Reputation: 12583

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.

Upvotes: 2

Vadim
Vadim

Reputation: 21714

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

Upvotes: 1

anishMarokey
anishMarokey

Reputation: 11397

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

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292685

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

Upvotes: 1

bobbymcr
bobbymcr

Reputation: 24177

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

return new MyItem(itemId, delegate() { MyFunction(myParam); });

Upvotes: 6

RaYell
RaYell

Reputation: 70454

It's the lambda expression.

Upvotes: 1

Related Questions