R# 5.1 Convert for loop to foreach loop not working

I have a problem trying to let Resharper 5.1.1753.4 convert a for-loop to a foreach-loop.

I have the following code:


var intArray = new[] { 1, 3, 5 };
for (var i = 0; i < intArray.Length; i++)
{
    Debug.WriteLine(intArray[i]);
}
Resharper suggests to convert the for loop into a foreach loop, which succeeds and changes the code into:

foreach (int t in intArray)
{
    Debug.WriteLine(t);
}
Which is fine, although it might have used var in stead of int.



Now, I try the following. I add .ToString() (I know it isn't needed here)
for (var i = 0; i < intArray.Length; i++)
{
    Debug.WriteLine(intArray[i].ToString());
}
This time, Resharper doesn't even suggest to convert the loop. Why not? ?:|

If I introduce a helper variable, it does offer to convert to foreach and does so successfully (acually, Resharpter introduces such a variable when you let it convert the foreach loop shown above back to a for-loop).
for (var i = 0; i < intArray.Length; i++)
{
    var thisInt = intArray[i];
    Debug.WriteLine(thisInt.ToString());
}


But now for the actual problem I have. This is the code:
var friends = new[] {
    new {name = "Tom", state = "IN"},
    new {name = "Alice", state = "VA"},
};
for (var i = 0; i < friends.Length; i++)
{
    Debug.WriteLine(friends[i].name);

}


Resharper shows the curly green line under for saying "For-loop can be converted into foreach-loop". The actions list shows the option "Convert to foreach". However, when I click that option, nothing happens... ?:|

So my problems/questions are:
1) Why doesn't Resharper offer to convert for to foreach in the second example.
2) Why doesn't a change occur after telling Resharper to convert in the last example.

1 comment
Comment actions Permalink

Hello Dick,

Those seem like bugs to me. I've created bug-reports in our tracker: http://youtrack.jetbrains.net/issue/RSRP-199888
and http://youtrack.jetbrains.net/issue/RSRP-199889. Thank you!

Andrey Serebryansky
Senior Support Engineer
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"

This is the code:
var friends = new[] {
new {name = "Tom", state = "IN"},
new {name = "Alice", state = "VA"},
};
for (var i = 0; i < friends.Length; i++)
{
Debug.WriteLine(friends[i].name);
}
Resharper shows the curly green line under for saying "For-loop can be
converted into foreach-loop". The actions list shows the option
"Convert to foreach". However, when I click that option, nothing
happens...



0

Please sign in to leave a comment.