Converting 'foreach' to 'for' loop or vice versa with ReSharper possible?
Yep ReShaper can do that. Tested it in VS2010 + R#5
Before:
var a = new int[] {1, 2, 3, 4};
foreach (var i in a)
{
}
After:
var a = new int[] {1, 2, 3, 4};
for (int index = 0; index < a.Length; index++)
{
var i = a[index];
}
You can even do this without Resharper now (Tested with Visual Studio 2017 on a C# project):
int[] array = new int[3] { 1, 2, 3 };
foreach (int item in array)
{
int someVariable = item;
//Your logic
}
Becomes
int[] array = new int[3] { 1, 2, 3 };
for (int i = 0; i < array.Length; i++)
{
int item = array[i];
int someVariable = item;
//Your logic
}
(And vice versa!) To make this change, you just have to click on the "foreach" or "for" word, and look for a screwdriver icon shown on the left, click on it and select "convert to 'for'" / "convert to 'foreach'". (see the link below if you never saw this icon)
Hope it helped someone (even if this is a very old post!)
Visual Studio screwdriver icon