Why IEnumerable is required in C# ? All you need to know | Explained with Example

 Use of IEnumerable in C# code is not new and We have already seen it being used in many places where we are dealing with Collection. Either it will be present as the return type and/or as parameter type. 

What is IEnumerable in C#?

IEnumerable is an Interface in C# which provides the capability to iterate over the Collection or in other words Enumerate over the collection which implements it.

Why IEnumerable?

Following are the reasons/should be the reasons for using IEnumerable 

  • It allows the use of For-each loop over the collection which is kind of a range based for loop in C#.
  • It abstracts the under lying data structure which holds the actual data.
  • Modification of the collection data is prevented when collection is exposed as IEnumerable.

Second point is the most important one for the use of IEnumerable, where it can act as a generic collection and the underlying data structure is not exposed outside. We can see these in action with the below example:

Sample Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace DesignPatterns
{
    class Program
    {
        static void Main(string[] args)
        {
            var days = new List<string>()
            {
                "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"
            };

            var months = new ArrayList()
            {
                "Jan","Feb","March","April","May","June","July","August","September","October","November","December"
            };

            Print(days);

            Print(months);
        }

        private static void Print(IEnumerable items)
        {
            foreach (var item in items)
            {
                Console.WriteLine(item);
            }
        }
    }
}

In the above example we have generic Print API which accepts IEnumerable where we are passing both List and ArrayList.

Therefore Print API is not aware of whether the Collection passed to it is of List type or ArrayList.

Following is the output of the above code:

Program output using IEnumerable


If we see from the Design Principle point of view, it implements Iterator Pattern where the storage/management of the actual data is abstracted and only enumeration over the collection is permitted.

Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Step By Step Guide to Detect Heap Corruption in Windows Easily

How to dynamically add Properties in C# .NET?