Skip to content

ArgumentException is thrown by foreach statement refactoring code #26748

@gewarren

Description

@gewarren

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:

  1. Given the following C# code:

int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D) { System.Console.Write($"{i} "); }

  1. 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} ");
}

  1. 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.

Metadata

Metadata

Assignees

Labels

Area-IDEBugResolution-FixedThe bug has been fixed and/or the requested behavior has been implemented

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions