Difference between IEnumerable and IEnumerator.

  1. IEnumerable uses IEnumerator internally.
  2. IEnumerable doesn’t know which item/object is executing.
  3. IEnumerator knows the current position of item/object.
  4. IEnumerable doesn't know the current position of item/object
  5. IEnumerable has one method, GetEnumerator ()
  1. // Difference between IEnumerable and IEnumerator.
  2. public class Program {
  3. public static void Main(string[] args) {
  4. IEnumerable_Example();
  5. }
  6. static void IEnumerable_Example() {
  7. List < string > Month = new List < string > ();
  8. Month.Add("January");
  9. Month.Add("February");
  10. Month.Add("March");
  11. Month.Add("April");
  12. Month.Add("May");
  13. Month.Add("June");
  14. Month.Add("July");
  15. Month.Add("August");
  16. Month.Add("September");
  17. Month.Add("October");
  18. Month.Add("November");
  19. Month.Add("December");
  20. IEnumerable < string > IEnumerable_ = (IEnumerable < string > ) Month;
  21. Console.WriteLine("IEnumerable_Example() Executing");
  22. Console.WriteLine("------------IEnumerable Returning items using foreach----------------");
  23. foreach(string i in IEnumerable_) {
  24. Console.WriteLine(i);
  25. }
  26. IEnumerator_Example(IEnumerable_);
  27. }
  28. static public void IEnumerator_Example(IEnumerable enumerable) {
  29. IEnumerator enumerator = enumerable.GetEnumerator();
  30. Console.WriteLine("----------IEnumerator_Example() Executing------------");
  31. while (enumerator.MoveNext()) {
  32. Console.WriteLine("----" + enumerator.Current.ToString() + "----");
  33. }
  34. Console.ReadLine();
  35. }
  36. }