Understanding IEnumerable in C#

In this post, I am going to discuss IEnumerable, why we are using IEnumerable and what is the importance of using IEnumerable. understand all these, let us start with a simple example.

Consider a class named a person, now I have a list of a certain number of students. and my aim is to loop all the person and display. here is the sample code.

the above person class contains only two property FirstName and LastName. now I am going to use this class in my program and print all the person class in a console application.

as you can see above, in this program I have created an array of Person and I can able to access the array in a foreach loop. Here comes a question,

Here comes a question,

  • what is the use of IEnumerable interface?
  • why do I need to implement the IEnumerable interface?

Answer : You don’t need to implement IEnumerable as a code implementor,But you need to implement if you want to expose your implementation to your client, and at the same time you don’t want your client to get confused with unwanted details.

IEnumerable interface implementation is completely for abstraction.

Ok let me talk about IEnumerable, IEnumerable can be found under two namespace

  • System.Collections
  • System.Collections.Generic  ( to implement Generic enumeration)

Here is the example for IEnumerable. which involves the following steps,

  • Define a class which needs to be enumerable
  • Define a class which implements IEnumerable
  • You must Implement IEnumerator, when you implement IEnumerable .
  • While we implement IEnumerator, we must implement the following following method and property
    • MoveNext – Method
    • Reset – Method
    • Current –  property

set breakpoint in the code and debug it. so that you can able to understand more.

ienumerable sample program

IEnumerable Program

IEnumerable Employee

IEnumerable Employee

IEnumerable employeeenum for enumerate the person objects

IEnumerable employeeenum for enumerate the person objects

Other reference links:

http://stackoverflow.com/questions/13902310/why-do-we-need-ienumerator-and-ienumerable

https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx

post your thoughts in the comments section below in the comment section.

0 comments… add one

Leave a Comment