[BUG REPORT] Incorrect Linq refactoring, Resharper version 5.1.1766.4
[BUG REPORT] Incorrect Linq refactoring, Resharper version 5.1.1766.4
Consider the following code:
using System;
using System.Collections.Generic;
namespace Demo
{
class Program
{
static void Main()
{
int count = 0;
Outer outer = new Outer();
foreach (Inner inner in outer.Items)
{
// Use Resharper to refactor the following loop to Linq:
foreach (Item item in inner.Items)
{
if (item.State)
{
count++;
}
}
}
Console.WriteLine(count); // Should be 9.
}
}
public class Item
{
public bool State
{
get
{
return true;
}
}
}
public class Outer
{
public IEnumerable<Inner> Items
{
get
{
yield return new Inner();
yield return new Inner();
yield return new Inner();
}
}
}
public class Inner
{
public IEnumerable<Item> Items
{
get
{
yield return new Item();
yield return new Item();
yield return new Item();
}
}
}
}
If you run this code, you will get an answer of 9.
Now use Resharper to refactor the second foreach loop to Linq. It is refactored as follows:
count = inner.Items.Count(item => item.State);
Clearly this is wrong - "count" is now reinitialised for each iteration of the outer loop. This results in an answer of 3 instead of 9.
The correct refactoring would be:
count += inner.Items.Count(item => item.State);
Please sign in to leave a comment.
Hi, Matthew
It seems to be fixed in R# 6.0 EAP builds.
--
Kirill Falk
.NET Team QA Lead
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"