Thursday, 19 June 2008

Resharper 4.0 and Lambda Expressions

Now I'm fairly new to the wonderful world of Resharper, so barely a day goes by where I don't discover something new about it, or through it. But today I found a feature that just made me want to share about it straight away.

Let me set the scene.

I'm coding a Lambda expression for use as a predicate and when finished I notice the now familiar little light bulb. Hmmm I thought, now what could Resharper be wanting to tell me about my code?

Resharper offers conversion from Lambda to statement, and to anonymous method.(real code replaced throughout to protect the innocent)

That's right Resharper is offering to convert my Lambda to either an anonymous method or a statement! So let's see what it does to the code if I choose these options.

Well If I choose the option 'Lambda expression to statement it turns my code into this:

The same code as inline statement.Note with this option I am given the choice to now convert on to an expression, or to an anonymous method.

If I choose the option 'To anonymous method' my code looks like this:

The same code as anonymous method. Note that it is offering to convert my code back to a lambda

If I choose the 'Lambda expression to anonymous method' option and place the caret in to the delegate keyword then I get a different option however.

Different Resharper options with the anonymous method.

This time the options include one to convert my anonymous method to a named method. Choosing this does what you will no doubt expect. It creates named method.

private static bool NewPredicate(Person p)
{ return p.Name == "Sue"; }

and changes my code to read:

Person sue = people.Find(NewPredicate);

Actually I added the prefix new, as Resharper just put Predicate, but you get the idea. Of course, Resharper now gives me the option to inline my Predicate as either an anonymous method, or as a Lambda.

Resharper offering to inline my named delegate method.

Neat huh!

Choosing to inline as an anonymous method acts as I would expect, and puts the code back to be the same as the anonymous version above. Choosing to inline as a Lambda however a have a tiny, tiny gripe with.

Resharper offering to remove the 'redundant parenthesis' that it inserted.

As you can see above, Resharper has placed the target variable within brackets. Still, at least Resharper knows that it shouldn't have done this, as it offers to remove them!

What I really, really like most about this, and made me want to blog about it, it that it very neatly highlights some of the evolution of C# from version 1 with its' named delegates (though of course we didn't have delegate comparisons then), through version 2, with its' anonymous methods, through to the current version 3 with its' Lambda goodness.

No comments: