The differences between IEnumerable and List in C#

Let’s explore the differences between IEnumerable and List in C#:

  1. IEnumerable:

    • Behavior Description: IEnumerable describes behavior rather than providing a concrete implementation.
    • Deferred Execution: When you use IEnumerable, you allow the compiler to defer work until later. The actual execution occurs only when you enumerate the collection (e.g., using a foreach loop or LINQ methods).
    • Optimization Opportunity: By specifying behavior only, you give LINQ a chance to optimize the program during enumeration.
    • Example:
      public IEnumerable<Animal> AllSpotted()
      {
          return from a in Zoo.Animals where a.Coat.HasSpots select a;
      }
      
      Here, the query is defined, but execution is deferred until you actually enumerate the result.
  2. List:

    • Implementation: List is an implementation of the IEnumerable behavior.
    • Immediate Execution: When you use ToList(), you force the compiler to materialize the results immediately (i.e., create a list with all the elements).
    • Adding and Removing Items: With a List<T>, you can add and remove items dynamically.
    • Example:
      List<Animal> sel = (from animal in Animals
                          join race in Species on animal.SpeciesKey equals race.SpeciesKey
                          select animal).Distinct().ToList();
      
      Here, sel is a list containing the distinct animals.
  3. Summary:

    • Use IEnumerable when you want to describe behavior and allow deferred execution.
    • Use List when you need a concrete collection with immediate execution and the ability to modify its contents.
    • Any modifications will change underlying collection if we are using IEnumerable as it keep reference of parent collection underlying collection.

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form