". I saw how it was used in the constructor: return new MyItem...">

C # 3.0 Value of expression () =>

What is the meaning of this expression "() =>". I saw how it was used in the constructor:

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

thanks

+3
source share
7 answers

This is a parameterless delegate written as lambda. Same as:

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

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

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

, . , MyItem.

MyItem(int itemId, Action action)

, () = > {} . MyItem :

MyItem(int itemId, Expression<Action> expression)

() = > {} , .. MyItem , , () = > {}. Linq , , Linq2Sql, LinqProvider , , SQL- .

() = > {} .

+2
+1

, ,

+1

ya .

+1
source

Here are simple examples of the lambda that 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

+1
source

Source: https://habr.com/ru/post/1717520/


All Articles