I am getting an unexpected starting value for a list collection when I iterate through the list with the following code:
var lister = new List<int>();
for (int i = 0; i <= 300; i++)
{
lister.Add(i);
}
foreach (var item in lister)
{
Console.WriteLine(item);
}
The the first output to the console is 2 and not a 0 as expected. If I do this with an array, it works fine as expected. In other words, the output to the console starts with 0. Why is the for loop above not adding values to the lister collection object starting from 0, instead it starts adding values from the number 2 and on wards?
This problem does not happen when I iterate thorough an array with the following code:
var myArray = new int[300];
for (int i = 0; i < 300; i++)
{
myArray[i] = i;
}
foreach (var item in myArray)
{
Console.WriteLine(item);
}