tags:

views:

263

answers:

5

For instance:

Sorter.SortBy ( array, ( a, b ) =>
{
    return a > b;
} );

What's the best way to format them for maximum readibility?

Also think of it for one parameter lambda version, and other cases that might be used commonly.

What are the guidelines?

+1  A: 

Why the curly brackets in your example? Don't you think this is more readable? :

Sorter.SortBy ( array, (a,b) => (a > b) );

EDIT (in response to comments):

If your lambda requires temporary variables or other stuff that can't be expressed in a single expression, you should use the curly brackets and an explicit return statement. In all (well, most) other cases it's cleaner to omit them, because it looks more intuitive (to me anyway).

Philippe Leybaert
It is. I just didn't know that would be possible.
Joan Venge
Also what if the lambda is very complex, how would you format it? Like into several lines?
Joan Venge
yes :) It's all a matter of personal preference. As long as you can read the developer's intentions, it's ok IMHO
Philippe Leybaert
A: 

You're going to have trouble deciding what formatting strategy is best since this is usually very subjective.

You could have a look at how ReSharper does it, since it allows you to customize the formatting a bit.

Christo
+1  A: 
Sorter.SortBy(array, (a, b) => a > b);
SLaks
+1  A: 
Sorter.Filter(array, a => a.IsOK);

Sorter.SortBy(array, (a, b) => a > b);

Collection.Apply(array, (a)       => a * a, // i like lining things up
                        (x, y, z) => WhipIt(x, y) / z,
                        (a, b)    => a + b);

Evaluator.Confuse(array, (a, func) =>  // this is a big one, engage curly braces
{
    if(a.Flag) return 0;
    else
    {
        var x = func(a);
        if(x < 0) return -1;
        else return x * 2;
    }
});
mquander
A: 

When dealing with complex lambdas (more than just one line, in my opinion), I actually prefer to regress to the old-fashioned 2.0 anonymous methods:

DoSomething(
   delegate (int a, int b)
   {
      int c = a + b;
      int d = /* blah blah */
      return d;
   });

When the lambda contains more than just one line, I like to see the types of the parameters instead of just (a, b). But that's just me.

Joe Enos