Maxim Gershkovich
Maxim Gershkovich

Reputation: 47179

General Lambda syntax question

So I seem to be confident that the following 2 statements are the same

List<object> values = new List<object>();
values.ForEach(value => System.Diagnostics.Debug.WriteLine(value.ToString()));

AND

List<object> values = new List<object>();
values.ForEach((object value) => { 
    System.Diagnostics.Debug.WriteLine(value.ToString());
});

AND I know I can insert multiple lines of code in the second example like

List<object> values = new List<object>();
values.ForEach((object value) => { 
    System.Diagnostics.Debug.WriteLine(value.ToString());
    System.Diagnostics.Debug.WriteLine("Some other action");
});

BUT can you do the same thing in the first example? I can't seem to work out a way.

Upvotes: 4

Views: 216

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500515

As others have shown, you can use a statement lambda (with braces) to do this:

parameter-list => { statements; }

However, it's worth noting that this has a restriction: you can't convert a statement lambda into an expression tree, only a delegate. So for example, this works:

Func<int> x = () => { return 5; };

But this doesn't:

Expression<Func<int>> y = () => { return 5; };

Upvotes: 1

Jeff Machamer
Jeff Machamer

Reputation: 942

The only real difference between the first and the second is the { }. Add that to the first one and you can then add as many lines as you want. It isn't the (object value) that is allowing you to add multiple lines.

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273244

This works fine:

values.ForEach(value =>
        { System.Diagnostics.Debug.WriteLine(value.ToString()); }
);

Maybe you forgot the ;

Upvotes: 2

Bashir Magomedov
Bashir Magomedov

Reputation: 2881

Yes you can :)

        List<object> values = new List<object>();
        values.ForEach(value =>
                           {
                               System.Diagnostics.Debug.WriteLine(value.ToString());
                               System.Diagnostics.Debug.WriteLine("Some other action");
                           }

            );

Upvotes: 9

Related Questions