Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference in List<string> and IEnumerable<string>

Tags:

c#

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);
}
like image 221
haydnD Avatar asked May 09 '12 19:05

haydnD


Video Answer


1 Answers

IEnumerable<string> is an interface. List<string> is a class that implements that interface.

An interface simply defines functionality that a class that implements that interface must implement.

The class is responsible for actually implementing that functionality.

Your test is actually testing the speed of iterating through a List<string> and a string[]. With the small size of the sample and the inner workings of the List<string> class, you really shouldn't see a difference.

like image 67
Justin Niessner Avatar answered Oct 13 '22 14:10

Justin Niessner