Important Interface in .NET: Work With IEnumerable Interface

This is our first presentation of the “Important Interface in C#” article series. I hope you can guess what this series is about. Yes, we will discuss a few important interfaces in the .NET class library, one in each article.

The purpose of the article is to explain the most important interface of the .NET class library and implement it in a pratical example. I hope this series will collect valuable information about various interfaces in one place with a suitable example.

So, without wasting time let's start with today's interface. This articles's targeted interface is “IEnumerable”. Yes, I hope this is the most used interface in applications and you will agree with me unconditionally.

Namespace

This interface is located in the following namespace:

System.Collections

Methods

GetEnumerator: Returns an enumerator that iterates through a collection.

Let's start to talk about the IEnumerable interface. It is the base interface for all non-generic collections that can be enumerated. If we implement the IEnumerable interface in our own collection then we can traverse the collection using a foreach loop (we will implement it shortly).

Version of IEnumerable interface

There are two versions of the IEnumerable interface in the .NET class library. They are:

  • IEnumerable :Without parameter
  • IEnumerable<T> :With parameter of type T (in other words any type)

Let's understand them practically with a small example.

Implementation of IEnumerable (without type parameter)

This is the example of an IEnumerable implementation without parameters. Just we have taken one string array and then applying LINQ to get all names from the string array to IEnumerable.

static void Main(string[] args)
{
    string []name ={"Sourav","Ram"};
    IEnumerable enu = from n in name select n;
    foreach (string n in name)
    {
        Console.WriteLine(n);
    }
    Console.ReadLine();
}

Then we are using a foreach loop to go through all values. Here is the output of the example above.

Implementation of IEnumerable

Implementation of IEnumerable<T>

We will now implement IEnumerable<T> to iterate a string array. The implementation is very similar to the previous one except the parameter. Since the parameter is a “T” type we can pass anything (almost) instead of T. In this example we are passing a string because we want to traverse the string collection. If necessary we can pass any predefined data type, as well as user defined data type. Have a look at the following example.

static void Main(string[] args)
{
    string []name ={"Sourav","Ram"};
    IEnumerable<string>  enu = from n in name select n;
    foreach (string n in name)
    {
        Console.WriteLine(n);
    }
    Console.ReadLine();
}

Here is the output.

Implementation of IEnumerable1

Implement IEnumerable in custom class

Fine, I hope you have understood the basic implementation of the IEnumerable interface in the previous two examples. As we explained earlier, if we implement an IEnumerable interface in our own class then we will be able to iterate the class object(s) using a foreach loop. Let's implement the idea.

Since IEnumerable contains only one method (GetEnumerator) we need to implement this method in our own class. Have a look at the following example.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SelfHostingWebAPI
{
    class Person : IEnumerable
    {
        public string name { get; set; }
        public string surname { get; set; }
        Object[] p = new Object[2];
        Int32 Index = 0;
        public void AddPerson(Object O)
        {
            p[Index] = O;
            Index++;
        }
        public IEnumerator GetEnumerator()
        {
            foreach (Object o in p)
            {
                if (o == null)
                    break;
                else
                    yield return o;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Person p1 = new Person();
            p1.name = "Sourav";
            p1.surname = "Kayal";
            Person p2 = new Person();
            p2.name = "Ram";
            p2.surname = "Das";
            p.AddPerson(p1);
            p.AddPerson(p2);
            foreach (Person ob in p)
            {
                Console.WriteLine(ob.name + " " + ob.surname);
            }
            Console.ReadLine();
        }
    }
}

The AddPerson() function will add a person object into the collection and then the GetEnumerator() method will return the person objects one by one using the “yield” keyword. Here is the output of the example above.

Implement IEnumerable in custom class

Implement Ienumerable<T> in custom class

In this example we will implement an IEnumerable<T> interface in our own class. The example is very similar to the previous example except we are passing an argument to the IEnumerable interface. Here we are implementing IEnumerable<Person> for the Person class. Yes, the argument and the class is the same.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SelfHostingWebAPI
{
    class Person  : IEnumerable<Person>
    {
        public string name { get; set; }
        public string surname { get; set; }
        Object[] p = new Object[2];
        Int32 Index = 0;
        public void AddPerson(Object O)
        {
            p[Index] = O;
            Index++;
        }
        public IEnumerator<Person> GetEnumerator()
        {
            foreach (Person o in p)
            {
                if (o == null)
                    break;
                else
                    yield return o;
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Person p1 = new Person();
            p1.name = "Sourav";
            p1.surname = "Kayal";
            Person p2 = new Person();
            p2.name = "Srikant";
            p2.surname = "Chatterjee";
            p.AddPerson(p1);
            p.AddPerson(p2);
            foreach (Person ob in p)
            {
                Console.WriteLine(ob.name + " " + ob.surname);
            }
            Console.ReadLine();
        }
    }
}

The following is the output of the example above.

Implement IEnumerable in custom class1

Conclusion

This is our first leap of the “Important interfaces in .NET” journey. We have started with one most useful interface in the .NET class library. I hope this series will help developers that want to be better developers in Microsoft technologies (read C#). Have a happy day. Meet you shortly with send presentation.


Recommended Free Ebook
Similar Articles