If a foreach loop is used for a two-dimensional array and you apply the "convert to for" loop refactoring and then run the generated code, it throws an ArgumentException.
Steps:
- Given the following C# code:
int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D) { System.Console.Write($"{i} "); }
- Refactor it to a for loop using the refactoring:
int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
System.Collections.IList list = numbers2D;
for (int i1 = 0; i1 < list.Count; i1++)
{
int i = (int)list[i1];
System.Console.Write($"{i} ");
}
- Run the code.
Actual result
An ArgumentException is thrown:
Unhandled Exception: System.ArgumentException: Array was not a one-dimensional array.
at System.Array.GetValue(Int32 index)
at System.Array.System.Collections.IList.get_Item(Int32 index)
at csharp_console.Program.Print() in C:\Users\gewarren\source\repos\csharp-console\csharp-console\Program.cs:line 29
at csharp_console.Program.Main(String[] args) in C:\Users\gewarren\source\repos\csharp-console\csharp-console\Program.cs:line 12
Expected result
No runtime exception from auto-generated code.
If a foreach loop is used for a two-dimensional array and you apply the "convert to for" loop refactoring and then run the generated code, it throws an ArgumentException.
Steps:
int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D) { System.Console.Write($"{i} "); }
int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
System.Collections.IList list = numbers2D;
for (int i1 = 0; i1 < list.Count; i1++)
{
int i = (int)list[i1];
System.Console.Write($"{i} ");
}
Actual result
An ArgumentException is thrown:
Unhandled Exception: System.ArgumentException: Array was not a one-dimensional array.
at System.Array.GetValue(Int32 index)
at System.Array.System.Collections.IList.get_Item(Int32 index)
at csharp_console.Program.Print() in C:\Users\gewarren\source\repos\csharp-console\csharp-console\Program.cs:line 29
at csharp_console.Program.Main(String[] args) in C:\Users\gewarren\source\repos\csharp-console\csharp-console\Program.cs:line 12
Expected result
No runtime exception from auto-generated code.