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

//this method will return a different collection with different type based on the option provided
static IEnumerable<int> GetCollection(int option) {
						//create a list of numbers and initialize it
            List<int> numbersList = new List<int>() { 1, 2, 3, 4, 5 };
						//create a queue of numbers
            Queue<int> numbersQueue = new Queue<int>();
            //add values to the queue
						numbersQueue.Enqueue(6);
            numbersQueue.Enqueue(7);
            numbersQueue.Enqueue(8);
            numbersQueue.Enqueue(9);
            numbersQueue.Enqueue(10);
						//if the option is 1
            if (option == 1) {
	              //return the list of type List<int>
                return numbersList;
            //if the option is 2
            } else if (option == 2) { 
		            //return the queue of type<int>
                return numbersQueue;
            //otherwise
            }else { 
                //return an array of numbers initialized with some numbers
                return new int[] {11,12,13,14,15 };
            }

}

initialized

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

using System;
using System.Collections;
using System.Collections.Generic;

namespace IEnumerableandIEnumerator {
    class Program {

        static void Main(string[] args) {

						//creating a generic IEnumerable variable that takes any collection of type int
						//we will use this variable to store the collections that will get returned by the GetCollection() method
						IEnumerable<int> unknownCollection;
            //call GetCollection() with option = 1 which will return a List<int> but we will store it in the base type of generic collections
            unknownCollection = GetCollection(1);

            Console.WriteLine("This was a List<int>");
            //for each number in the collection we got back from GetCollection(1);
						foreach(int num in unknownCollection) {
                Console.Write(num + " ");
            }
						//new line
            Console.WriteLine("");
						//call GetCollection() with option = 2 which will return a Queue<int> but we will store it in the base type of generic collections
            unknownCollection = GetCollection(2);
            
            Console.WriteLine("This was a Queue<int>");
            //for each number in the collection we got back from GetCollection(2);
					  foreach (int num in unknownCollection) {
                Console.Write(num + " ");
            }
						//new line
            Console.WriteLine("");
						//call GetCollection() with option = 5 which will return an array int[] but we will store it in the base type of generic collections
            unknownCollection = GetCollection(5);
						
            Console.WriteLine("This was an array of int");
            //for each number in the collection we got back from GetCollection(5);
						foreach (int num in unknownCollection) {
                Console.Write(num + " ");
            }
						//pause
            Console.ReadKey();
			  }
   }
}

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

//a method that takes any collection with elements of type <int> and will print the sum of the numbers in this collection
static void CollectionSum(IEnumerable<int> anyCollection) {
						//sum variable to store the sum of the numbers in anyCollection
            int sum = 0;
						//for each number in the collection passed to this method
            foreach (int num in anyCollection) {
							//add the num value to sum
	            sum +=num;
            }
						//print the sum
            Console.Write("Sum is {0}",sum);
}

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

using System;
using System.Collections;
using System.Collections.Generic;

namespace IEnumerableandIEnumerator {
    
		class Program {
	

        static void Main(string[] args) {
						//a list of type List<int> initialized with some number
						List<int> numberList = new List<int>() { 8, 6, 2 };
						// an array of type int[] initialized  with some numbers
            int[] numberArray = new int[] { 1, 7, 1, 3 };
            //new line
            Console.WriteLine(" ");
						//call CollectionSum() and pass the list to it 
            CollectionSum(numberList);
						//new line
            Console.WriteLine(" ");
						//call CollectionSum() and pass the array to it
            CollectionSum(numberArray);

						//pause
            Console.ReadKey();
        }
	}
}

The output of this application would be

 

Complete Code

using System;
using System.Collections;
using System.Collections.Generic;

namespace IEnumerableandIEnumerator {
    class Program {

        static void Main(string[] args) {

           //creating a generic IEnumerable variable that takes any collection of type int
						//we will use this variable to store the collections that will get returned by the GetCollection() method
						IEnumerable<int> unknownCollection;
            //call GetCollection() with option = 1 which will return a List<int> but we will store it in the base type of generic collections
            unknownCollection = GetCollection(1);

            Console.WriteLine("This was a List<int>");
            //for each number in the collection we got back from GetCollection(1);
						foreach(int num in unknownCollection) {
                Console.Write(num + " ");
            }
						//new line
            Console.WriteLine("");
						//call GetCollection() with option = 2 which will return a Queue<int> but we will store it in the base type of generic collections
            unknownCollection = GetCollection(2);
            
            Console.WriteLine("This was a Queue<int>");
            //for each number in the collection we got back from GetCollection(2);
					  foreach (int num in unknownCollection) {
                Console.Write(num + " ");
            }
						//new line
            Console.WriteLine("");
						//call GetCollection() with option = 5 which will return an array int[] but we will store it in the base type of generic collections
            unknownCollection = GetCollection(5);
						
            Console.WriteLine("This was an array of int");
            //for each number in the collection we got back from GetCollection(5);
						foreach (int num in unknownCollection) {
                Console.Write(num + " ");
            }
					
						//a list of type List<int> initialized with some number
						List<int> numberList = new List<int>() { 8, 6, 2 };
						// an array of type int[] initialized  with some numbers
            int[] numberArray = new int[] { 1, 7, 1, 3 };
            //new line
            Console.WriteLine(" ");
						//call CollectionSum() and pass the list to it 
            CollectionSum(numberList);
						//new line
            Console.WriteLine(" ");
						//call CollectionSum() and pass the array to it
            CollectionSum(numberArray);

						//pause
            Console.ReadKey();
        }

//this method will return a different collection with different type based on the option provided
static IEnumerable<int> GetCollection(int option) {
						//create a list of numbers and initialize it
            List<int> numbersList = new List<int>() { 1, 2, 3, 4, 5 };
						//create a queue of numbers
            Queue<int> numbersQueue = new Queue<int>();
            //add values to the queue
						numbersQueue.Enqueue(6);
            numbersQueue.Enqueue(7);
            numbersQueue.Enqueue(8);
            numbersQueue.Enqueue(9);
            numbersQueue.Enqueue(10);
						//if the option is 1
            if (option == 1) {
	              //return the list of type List<int>
                return numbersList;
            //if the option is 2
            } else if (option == 2) { 
		            //return the queue of type<int>
                return numbersQueue;
            //otherwise
            }else { 
                //return an array of numbers initialized with some numbers
                return new int[] {11,12,13,14,15 };
            }

}
     
//a method that takes any collection with elements of type <int> and will print the sum of the numbers in this collection
static void CollectionSum(IEnumerable<int> anyCollection) {
						//sum variable to store the sum of the numbers in anyCollection
            int sum = 0;
						//for each number in the collection passed to this method
            foreach (int num in anyCollection) {
							//add the num value to sum
	            sum +=num;
            }
						//print the sum
            Console.Write("Sum is {0}",sum);
}

    }

}
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