4

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.

1
  • If C# had the comma operator like in C or C++ then that could have been used to avoid the brackets. However, C# does not have the comma operator (except as an exception in for-loops). But C# does not have this operator, so it is somewhat irrelevant. Commented May 25, 2011 at 13:57

4 Answers 4

9

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");
                           }

            );
Sign up to request clarification or add additional context in comments.

1 Comment

also with typed properties, BlahObj.ForEach(value => { Debug.WriteLine(value.BlahProperty); });
2

This works fine:

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

Maybe you forgot the ;

3 Comments

+1: I also figured the OP would have forgotten the ;. Lolz at @o6tech who apparently doesn't read the questions too well
... apparently I don't. +1 to you :)
Well, after reading again, I still think my comment was valid. His first example (which he wanted to add multiple statements to), didn't include {}'s, so it's possible he was omitting them, no?
2

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.

Comments

1

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; };

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.