Difference between IEnumerable and IEnumerator.
- IEnumerable uses IEnumerator internally.
- IEnumerable doesn’t know which item/object is executing.
- IEnumerator knows the current position of item/object.
- IEnumerable doesn't know the current position of item/object
- IEnumerable has one method, GetEnumerator ()
-
- public class Program {
- public static void Main(string[] args) {
- IEnumerable_Example();
- }
- static void IEnumerable_Example() {
- List < string > Month = 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");
- IEnumerable < string > IEnumerable_ = (IEnumerable < string > ) Month;
- Console.WriteLine("IEnumerable_Example() Executing");
- Console.WriteLine("------------IEnumerable Returning items using foreach----------------");
- foreach(string i in IEnumerable_) {
- Console.WriteLine(i);
- }
- IEnumerator_Example(IEnumerable_);
- }
- static public void IEnumerator_Example(IEnumerable enumerable) {
- IEnumerator enumerator = enumerable.GetEnumerator();
- Console.WriteLine("----------IEnumerator_Example() Executing------------");
- while (enumerator.MoveNext()) {
- Console.WriteLine("----" + enumerator.Current.ToString() + "----");
- }
- Console.ReadLine();
- }
- }