Chintan Dave

Chintan Dave

  • 1.8k
  • 67
  • 6.9k

IEnumerable Interface

Aug 29 2018 5:35 AM
Suppose I have one list of strings in my main method. I can use foreach loop with lstMonth directly.
static void Main(string[] args)
{
List<string> lstMonth = new List<string>();
Month.Add("January");
Month.Add("February");
Month.Add("March");
Month.Add("April");
Month.Add("May");
Month.Add("June");
Month.Add("July");
Month.Add("August");
Month.Add("September");
Month.Add("October");
Month.Add("November");
Month.Add("December");
// First Loop
foreach(string str1 in lstMonth)
{
Console.WriteLine(str1);
}
}
Another method for reiterating through lstMonth is as below
IEnumerable<string> iEnumerableOfString = (IEnumerable<string>)Month;
// Second Loop
foreach(string AllMonths in iEnumerableOfString)
{
Console.WriteLine(AllMonths);
}
Reference Link : https://www.c-sharpcorner.com/UploadFile/219d4d/ienumerable-vs-ienumerator-in-C-Sharp/
Question: What is the difference between foreach loop of list of strings (First Loop) vs IEnumerable (Second Loop) ?
Do we get any advantage if we use second loop in terms of performance or any other ways ? If yes then please mention those ?
If no then why should we use it?

Answers (2)