A coworker of mine started with this code:
var newList = new List<>();
foreach(var item in otherList)
{
newList.Add(GetNewObjectFrom(item));
}
ReSharper correctly identified a use of LINQ here, and changed it to:
var newList = otherList.Select(o => GetNewObjectFrom(o)).ToList();
However, the lambda is unnecessary, and could be simplified further by just passing the method:
var newList = otherList.Select(GetNewObjectFrom).ToList();
My question:
Can any tool within Visual Studio 2010 Professional, or various arm-twisting of ReSharper, detect this change that should be made? I realize that the best tool is a second set of human eyes, and that’s where this question comes from to begin with … but the more of my job that’s done by computers, the better.
edit: awesome, it’s a ReSharper bug. Here’s a sample program:
using System.Linq;
namespace ResharperMethodGroupBug
{
class Program
{
static void Main(string[] args)
{
var program = new NumberProgram(new NumberProcessor());
program.Run();
}
}
class NumberProgram
{
private readonly INumberProcessor numberProcessor;
public NumberProgram(INumberProcessor numberProcessor)
{
this.numberProcessor = numberProcessor;
}
static long SquareNumber(int n)
{
return n * n;
}
public void Run()
{
var listOfNumbers = Enumerable.Range(1, 100).ToList();
// appropriately triggers "convert to method group"
var listOfSquares = listOfNumbers.Select(n => SquareNumber(n));
// does not trigger "convert to method group" when it should
var listOfCubes = listOfNumbers.Select(n => this.numberProcessor.CubeNumber(n));
// proof that a method group works here
var anotherListOfCubes = listOfNumbers.Select(this.numberProcessor.CubeNumber);
}
}
interface INumberProcessor
{
long CubeNumber(int n);
}
class NumberProcessor : INumberProcessor
{
public long CubeNumber(int n)
{
return n * n * n;
}
}
}
edit 2: I’ve posted an issue on JetBrains’ Youtrack: http://youtrack.jetbrains.com/issue/RSRP-301259
Resharper already detects this and suggest the simplification:
(tested with VS2010 Pro SP1 and R# 5.1.3)