Let’s discuss some of the advantages of using the IEnumerable Interface

Since we know from OOP that we can store an instance of a child class in a variable it’s type is of the parent class in a process we call up casting

In a similar fashion we can store any collection that implements the IEnumerable interface into an instance of IEnumerable it self

This can be useful in situations where a method can return a different type of collection based on some rules or when we want to create methods that can take any collection to do some operations on it. This is very useful and will save us unnecessary overloads of the same method

Example 1

in this example, we have a method called GetCollection() which takes an int option

based on this option the method will return a different type of collection if the option value was

1 it will return a List<int>

and if the value was

2 it will return a Queue<int>

else it will return an array of int

in such cases we can’t just set the array return type to List<int> or anything else

because in other parts of the code we are returning a queue and sometimes an array

therefore setting the return type to IEnumerable<int> will solve the issue completely since all collections as we mentioned implements this interface


we can then call this method from the main like this.

The output of this App is :

Example 2

Similar to example 1 we can do the same thing with method parameters

Here we have this method called CollectionSum which takes an IEnumerable<int>

which will accept any kind of generic collection that takes T for int as its a type parameter

and will return the sum of elements of this collection

then we can call it from the main method like this

We a List<int> the first time and an array of int the second time using the same method

The output of this application would be


Complete Code