Let’s explore the differences between IEnumerable
and List
in C#:
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 aforeach
loop or LINQ methods). - Optimization Opportunity: By specifying behavior only, you give LINQ a chance to optimize the program during enumeration.
- Example:
Here, the query is defined, but execution is deferred until you actually enumerate the result.public IEnumerable<Animal> AllSpotted() { return from a in Zoo.Animals where a.Coat.HasSpots select a; }
- Behavior Description:
List
:- Implementation:
List
is an implementation of theIEnumerable
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:
Here,List<Animal> sel = (from animal in Animals join race in Species on animal.SpeciesKey equals race.SpeciesKey select animal).Distinct().ToList();
sel
is a list containing the distinct animals.
- Implementation:
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.
- Use
Tags
C#