Why next code generates loop hangs?
var x = new
{
Items = new List<int> { 1, 2, 3 }.GetEnumerator()
};
while (x.Items.MoveNext())
Console.WriteLine(x.Items.Current);
If I get enumerator after x initialization, than everything works fine:
var x = new
{
Items = new List<int> { 1, 2, 3 }
};
var enumerator = x.Items.GetEnumerator();
while (enumerator.MoveNext())
Console.WriteLine(enumerator.Current);
Tried to decompile both code blocks, but don't understand the reason:
List<int> intList = new List<int>();
intList.Add(1);
intList.Add(2);
intList.Add(3);
var data1 = new \u003C\u003Ef__AnonymousType0<List<int>.Enumerator>(intList.GetEnumerator());
while (true)
{
List<int>.Enumerator items = data1.Items;
if (items.MoveNext())
{
items = data1.Items;
Console.WriteLine(items.Current);
}
else
break;
}
List<int> Items = new List<int>();
Items.Add(1);
Items.Add(2);
Items.Add(3);
var data2 = new \u003C\u003Ef__AnonymousType0<List<int>>(Items);
List<int>.Enumerator enumerator = data2.Items.GetEnumerator();
while (enumerator.MoveNext())
Console.WriteLine(enumerator.Current);