These two seem to be doing the exact thing. I timed them – knowing this is a small example – but they seem to run at the exact same speed as well. Is there a benefit of using one over the other?
List<string> alpha = new List<string>(new string[] { "a", "b", "c" });
foreach (var letter in alpha)
{
Console.WriteLine(letter);
}
IEnumerable<string> _alpha = new[] {"a", "b", "c"};
foreach(var _letter in _alpha)
{
Console.WriteLine(_letter);
}
They are different type of objects, with
IEnumerablebeing an interface (not instance itself, just a schema for some functionality) whileListis actual class.There is sort of an “advantage” to using one over the other.
If you are writing a method which you want to be more flexible, and only needs to enumerate through the objects, then use
IEnumerable.ListimplementsIEnumerable, and can be treated as such, just likeCollection, and many other classes.Take this for example:
Then you have this data:
These all work:
And these do not: