IEnumerable vs ICollection vs IList vs List in C#

In this article, we will discuss the usage of IEnumerable vs ICollection vs IList vs List in C#, as well as when to use each of them. Their explanations will help us decide what should be included in our code, and their useful coding examples will make our process easier. At end of this article, you will come to understand the whole concept of these interfaces and collections.

A list or container that can hold some things is called an IEnumerable. All of the elements in the IEnumerable can be iterated through. Instead of using a container to hold a list of items, you can only add, delete, update, and so on. This form of list container is the most fundamental. An IEnumerable just contains an enumerator to assist in iterating over the elements. You must iterate over the list's elements to obtain the item count because an IEnumerable does not even save the number of things in the list.

Whereas, Another collection type that enhances IEnumerable's functionality to add, remove, and update elements in the list is called ICollection. The ICollection also keeps track of the number of items it contains, so we don't have to loop through every member to determine the overall number of elements. It takes O(1) time to retrieve the total item count. ICollection has the following features: enumerating the elements, filtering the elements, adding new elements, deleting existing elements, updating existing elements, and obtaining the number of items in the list that are currently available.

IList extends ICollection. In addition to the combined activities of IEnumerable and ICollection, an IList can also execute additional operations like adding or removing elements from the middle of a list. You can iterate over the elements using a foreach loop or a for a loop.

In case of Strongly typed objects can be found in the List<T> collection, which also has methods for sorting, searching, and list modification. It belongs to the System.Collections.Generic namespace and is an ArrayList in generic form. The highly typed list of objects represented by this generic list collection class can be accessed by using an integer index that begins at 0. It also offers a variety of tools for filtering, organizing, and searching the list of things.



When to use IEnumerable in C#:


The built-in interface IEnumerable in C# specifies a method for iterating over a group of elements. It serves to symbolize a list of items that can be repeated using a foreach loop. In C#, the IEnumerable interface is used to provide a way to iterate over a collection of items. It defines a single method, GetEnumerator(), which returns an IEnumerator that can be used to iterate over the collection. A simple iteration over a non-generic collection is supported by the enumerator that is provided.

IEnumerable is the most basic collection type in C#. It represents a sequence of elements that can be enumerated, but it does not provide any methods for modifying the sequence. Use IEnumerable when you need to iterate over a sequence of elements, but you don't need to modify the sequence. For example:


IEnumerable<int> numbers = new int[] { 1, 2, 3, 4, 5 };

foreach (int number in numbers)

{

Console.WriteLine(number);

}



Here are some scenarios where IEnumerable can be used:


Given below is an example of IEnumerable, When you want to iterate over a collection of objects using a foreach loop:

Example:


namespace CollectionsDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

  IEnumerable<string> fruits = new List<string>() { "Apple", "Banana", "Orange" };

            foreach (string fruit in fruits)

            {

                Console.WriteLine(fruit);

            }

            Console.WriteLine("Hello World!");

        }

    }

}



Output:


The output is : Apple

The output is : Banana

The output is : Orange




An example of an IEnumerable is provided below. When you want to return a collection of objects from a method:

Example:


namespace CollectionsDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

          public static IEnumerable<int> GetNumbers()

          {

              for (int i = 0; i < 10; i++)

              {

                  yield return i;

              }

          }

        }

        public static IEnumerable<int> GetNumbers()

        {

            for (int i = 0; i < 10; i++)

            {

                yield return i;

            }

        }

    }

}




Output:


The result is : 0

The result is : 1

The result is : 2

The result is : 3

The result is : 4

The result is : 5

The result is : 6

The result is : 7

The result is : 8

The result is : 9




Give below is another example of IEnumerable, When you want to filter or transform a collection of objects using LINQ:

Example:


namespace CollectionsDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

          IEnumerable<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };

          IEnumerable<int> evenNumbers = numbers.Where(n => n % 2 == 0);

          foreach (int number in evenNumbers)

          {

              Console.WriteLine("The even numbers are :" +number);

          }

        }

    }

}



Output:


The even numbers are :2

The even numbers are :4

The even numbers are :6

The even numbers are :8



Note: IEnumerable provides a way to iterate through a collection of objects in each of these situations without having to be aware of the collection's implementation. Deferred execution is also supported, which can boost efficiency and use less memory.



When to use ICollection in C#:


In C#, ICollection is an interface that represents a non-generic collection of objects that can be individually accessed by index. The ICollection interface inherits from IEnumerable, which means that all ICollection implementations must also be enumerable. The ICollection is useful when you need to work with a collection of objects, but you don't need the more specialized features of other collection interfaces like IList or IDictionary. In other words, we can say ICollection is useful when you want to create a collection of items that can be enumerated, but you don't need to access individual elements by index.

ICollection extends IEnumerable and adds methods for adding, removing, and checking if an element exists in the collection. Use ICollection when you need to modify a collection, but you don't need to access the elements by index.

Here are a few examples of when you might use ICollection:


Storing a collection of objects.

Example:

  

      static void Main(string[] args)

        {

      ICollection<string> myCollection = new List<string>(); // Create a new List<string> and assign it to myCollection

              myCollection.Add("apple");

            myCollection.Add("banana");

            myCollection.Add("cherry");

            myCollection.Add("Mango");

            foreach (string item in myCollection)

            {

                Console.WriteLine(item);

            }

        }



Output:


apple

banana

cherry

Mango




Checking if a collection contains a specific object.

Example:


internal class Program

    {

        static void Main(string[] args)

        {

       ICollection<string> myCollection = new List<string>(); // Create a new List<string> and assign it to myCollection

              myCollection.Add("apple");

            myCollection.Add("banana");

            myCollection.Add("cherry");

            myCollection.Add("Mango");

           if (myCollection.Contains("banana"))

           {

               Console.WriteLine("The collection contains 'banana'");

           }

        }

    }




Output:


The collection contains 'banana'





When to use IList in C#:


IList is an interface in C# that provides a way to access and manipulate a collection of elements. IList can be used when you need a collection that allows random access, insertion, and removal of elements, and also supports iterating over the elements in the collection.

IList extends ICollection and adds methods for accessing elements by index. Use IList when you need to access elements by index, and you need to modify the collection.

Here are some code examples to demonstrate the use of IList in C#:


Creating an IList of strings

Example:


namespace CollectionsDemo

{

    internal class Program

    {

  +      static void Main(string[] args)

        {

          IList<string> names = new List<string>();

          names.Add("David");

          names.Add("Smith");

          names.Add("Charlie");

          names.Add("Johnson");

          foreach (string item in names)

          {

              Console.WriteLine(item);

          }


    // Console.WriteLine(names[0]); // Output: "Alice"


   // Console.WriteLine(names[1]); // Output: "Bob"

    

  // Console.WriteLine(names[2]); // Output: "Charlie"

}

    }

}



Output:


David

Smith

Charlie

Johnson


In this example, we create an IList of strings using the List class. We then add four strings to the list using the Add method.


In C#, the IList interface is used to define a collection of items that can be also accessed by index. Given below is another example of using IList in C#, Where we have implemented the insertion, removal, modification, and iterating over the elements in the collection.

Example:


namespace CollectionsDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

            // Create an empty ArrayList and add some elements

            IList list = new ArrayList();

            list.Add("apple");

            list.Add("banana");

            list.Add("cherry");


            // Access individual items by index

            Console.WriteLine(list[0]);  // Output: apple

            Console.WriteLine(list[1]);  // Output: banana

            Console.WriteLine(list[2]);  // Output: cherry


            // Modify an item in the list

            list[1] = "orange";


            // Remove an item from the list

            list.RemoveAt(2);


            // Iterate over the list using a for loop

            for (int i = 0; i < list.Count; i++)

         
           {

                Console.WriteLine(list[i]);

         
            }
         

        }

    }

}




Output:


apple

banana

cherry

apple

orange





When to use List in C#:


In C#, a list is a dynamic data structure that can store a collection of elements of the same data type. It is a useful container to hold a collection of items where the size of the collection can vary over time.

List is a concrete implementation of IList. It provides the same methods as IList, but with better performance. Use List when you need to access elements by index and modify the collection frequently.

Here are some examples of when to use a list in C#:

When you need to store a collection of items of the same type.

Example:


List<int> numbers = new List<int>();

numbers.Add(1);

numbers.Add(2);

numbers.Add(3);




When you need to manipulate a collection of items by adding, removing, or modifying items.

Example:


List<string> colors = new List<string>();

colors.Add("Red");

colors.Add("Green");

colors.Add("Blue");

colors.RemoveAt(1); // Removes Green from the list

colors[0] = "Yellow"; // Replaces Red with Yellow




When you need to iterate over a collection of items using a loop.

Example:


List<double> prices = new List<double>();

prices.Add(10.0);

prices.Add(20.0);

prices.Add(30.0);

foreach (double price in prices)

{

    Console.WriteLine(price);

}




When you need to sort and search a collection of items.

Example:


internal class Program

    {

        static void Main(string[] args)

        {

          List<string> fruits = new List<string>();

          fruits.Add("Apple");

          fruits.Add("Banana");

          fruits.Add("Cherry");

          fruits.Add("Mango");


     // sorting of elements

      fruits.Sort();

          Console.WriteLine(fruits[1]);


    // searching elements


 int index = fruits.IndexOf("Cherry"); // Returns 1

         Console.WriteLine(index);


   }

 }



Output:


 Banana

 2




Here's a summary of when to use each interface:

       IEnumerable: read-only operations on a collection.

       ICollection: add or remove elements from a collection.

       IList: access elements in a collection by index.

       List: frequently add, remove, or modify elements in a collection.



Conclusion:


In C#, the interface IEnumerable defines the method GetEnumerator, which produces an IEnumerator interface as a result. For all nongeneric collections in C#, the ICollection interface specifies the size, enumerators, and synchronization techniques. IList is an interface that represents a collection of objects which can be accessed by index. In C# the elements of the List can be accessed through its index number using ‘for’ or ‘foreach’ loop.

Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.


Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee