Question about inconsistent code generation while using "foreach" and "List<T>" #106817
-
I have those methods: static void ListForEach(List<int> numbers)
{
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
static void ListFor(List<int> numbers)
{
for (int i = 0; i < numbers.Count; i++)
{
Console.WriteLine(numbers[i]);
}
}
static void ArrayForEach(int[] numbers)
{
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
static void ArrayFor(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
} They generate something like this: [NullableContext(1)]
[CompilerGenerated]
internal static void <<Main>$>g__ListForEach|0_0(List<int> numbers)
{
List<int>.Enumerator enumerator = numbers.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}
finally
{
((IDisposable)enumerator).Dispose();
}
}
[NullableContext(1)]
[CompilerGenerated]
internal static void <<Main>$>g__ListFor|0_1(List<int> numbers)
{
int num = 0;
while (num < numbers.Count)
{
Console.WriteLine(numbers[num]);
num++;
}
}
[NullableContext(1)]
[CompilerGenerated]
internal static void <<Main>$>g__ArrayForEach|0_2(int[] numbers)
{
int num = 0;
while (num < numbers.Length)
{
Console.WriteLine(numbers[num]);
num++;
}
}
[NullableContext(1)]
[CompilerGenerated]
internal static void <<Main>$>g__ArrayFor|0_3(int[] numbers)
{
int num = 0;
while (num < numbers.Length)
{
Console.WriteLine(numbers[num]);
num++;
}
} Why only |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
ListForEach
uses List<T>.Enumerator.MoveNext(), which throws InvalidOperationException if the list has been modified after the enumerator was created.ListFor
andArrayFor
don't check that because they use just an integer index rather than a enumerator object.ArrayForEach
doesn't check that because arrays don't keep track of modifications.