Anupam Mishra

Total Post:135

Posted by  Anupam Mishra
C#  .NET 
 1257  View(s)
Rate this:
Hi Everyone,
I am now using collections in c#. So , i want to please anyone can  give me a brief intro with implementation of IEnumerable<>  interface.

Thank You.
  1. Anupam Mishra


    Re: What is IEnumerable<> in C#?

    In C# collection defines a non-generic IEnumerable interface and there is a generic type-safe IEnumerable<T> interface.

    The IEnumerable interface is located in the System.Collections namespace and contains only a single method definition. The interface definition looks like this:


    public interface IEnumerable
        IEnumerator GetEnumerator();

    The GetEnumerator method must return an instance of an object of a class which implements the IEnumerator interface. I am not going to details. if you are interested, please visit the  msdn documentation.

    It is important to know that the C# language foreach keyword works with all types that implement the IEnumerable interface. Only in C# it also works with things that don’t explicitly implement IEnumerable or IEnumerable<T>. I believe you have been using the foreach keyword many times and without worrying about the reason why and how it worked with that type.


    Let’s now take a look at the definition of the generic and type-safe version called IEnumerable<T> which is located in the System.Collections.Generic namespace:


    public interface IEnumerable<out T> : IEnumerable


        IEnumerator<T> GetEnumerator();


    As you can see the IEnumerable<T> interface inherits from the IEnumerable interface. Therefore a type which implements IEnumerable<T> has also to implement the members of IEnumerable.

    IEnumerable<T> defines a single method GetEnumerator which returns an instance of an object that implements the IEnumerator<T> interface. We won’t have a look at this interface this time. Please take a look at the msdn documentation if you would like to get some more information.


    IEnumerator<string> IEnumerable<string>.GetEnumerator()      //Generic
          Console.WriteLine("Hi Guest");
          return this.elements.GetEnumerator();
     //Non Generic
        IEnumerator IEnumerable.GetEnumerator()
          return this.elements.GetEnumerator();

      Modified On Apr-11-2018 01:03:39 AM



Enter your email address here always to be updated. We promise not to spam!