ReSharper and the Method Group Refactor

While writing code similar to the following lines, ReSharper suggested the “Replace With Method Group” Refactoring for Line 2.
 
   1: var names = Directory.GetFiles(@"c:\Program Files").ToList();

   2: names.ForEach(n => Console.WriteLine(n));

The Method Group shorthand is usually found in places where you take the following code

myButton.Click += new EventHandler(myButton_Click);

and replace it with this.

myButton.Click += myButton_Click;

The C# compiler can infer the usage of the EventHandler class, giving you cleaner, less noisy code.

Letting Resharper apply the Method Group refactoring produces the following code.
   1: var names = Directory.GetFiles(@"c:\ProgramFiles").ToList();

   2: names.ForEach(Console.WriteLine);

 
I was pleasantly surprised by the results. Apparently, I don’t have to explicitly declare the intermediate lambda variable ‘n’ just so I can pass it into the WriteLine method. The compiler is smart enough to infer this for me.  Although a little confusing at first, this shorthand notation is pretty nice.  I doubt I would have realized this without ReSharpers’ refactoring suggestions, one of the many reasons I’m a R# Junkie.

3 Comments

  • R.Lawson says:

    Last time I tried R# with VS2010 the performance was insanely slow – even on a powerful laptop. So I moved to JustCode. Did they fix the performance issues?

  • randypatterson says:

    Both the beta of VS2010 and R# were very slow. Speed has improved greatly since then and I don’t notice any slowness with R# loaded.

  • Codehead says:

    Agreed, no real performance issues with R# and 2010, except startup/project load which is a little slow.

    However, regardless of that I can’t help thinking these types of Refactoring actually make the code less readable…
    Yes, they slim down the actual code, but this is one of those obscure ones that if I used it, it would probably incur more time costs with people having to work out what is actually going on than if it were written ‘longhand’