I hope i don't get slammed for asking something so basic. I could Google for the answer, but I want to hear something that's not from a textbook.
I'm writing a unit test to verify that my IDictionary
Keys are sequential.
Since the Keys
property is an ICollection<T>
, I want to enumerate over the collection and print the Key values to the console.
When attempting to print the Key values using a simple for
loop:
for (int i = 0; i < unPivotedData.Count; i++)
{
Console.WriteLine(unPivotedData.Keys[i]);
}
I received the following compile error:
Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.ICollection<int>'
However, when I used the foreach
loop:
foreach(int key in unPivotedData.Keys)
{
Console.WriteLine(key);
}
Everything worked just fine.
I understand what an indexer does and how it's implemented, but how does the foreach
work? I don't understand how the foreach
can work yet the for
results in a compiler error.
Am I missing a fundamental of Enumeration here?
Cheers!
EDIT:
Furthermore, is there a performance difference between the two? I know I cannot use for
with an IDictionary but if I'm using an IList, I can. Does the for
move quicker than the foreach
or is the performance gain negligible