Skip to content

The advantages of the IEnumerable Interface

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

Introduction

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

initialized

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

The output of this App is :

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2470d277-b011-41cc-a2f9-44fa91a7fb29/Untitled.png

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

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide