π Introduction
When learning C#, many beginners get confused between:
Both are used to store collections of data.
But questions arise:
In this article, we will understand everything in very simple words, with real examples and output.
π§ What is IEnumerable?
IEnumerable is an interface in C#.
It is used for:
π Reading data
π Looping through data
π Returning collection of items
It allows only iteration (looping).
β
Example of IEnumerable :
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
IEnumerable<string> names = new List<string>()
{
"Rahul",
"Amit",
"Neha"
};
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output
Rahul
Amit
Neha
π§ What is List?
List<T> is a collection class.
It:
β Stores data
β Allows add/remove
β Allows indexing
β Allows modification
It is more powerful than IEnumerable.
β
Example of List :
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string>();
names.Add("Rahul");
names.Add("Amit");
names.Add("Neha");
names.Remove("Amit");
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output
Rahul
Neha
π Key Difference Between IEnumerable and List :
| Feature | IEnumerable | List |
|---|
| Type | Interface | Class |
| Add/Remove | β No | β
Yes |
| Modify Data | β No | β
Yes |
| Index Access | β No | β
Yes |
| Best For | Read-only data | Read + Write data |
π― When Should You Use IEnumerable?
Use IEnumerable when:
β You only want to read data
β You donβt want data modification
β You are returning data from method
β You want better performance
Example:
public IEnumerable<string> GetNames()
{
return new List<string> { "Rahul", "Amit" };
}
π― When Should You Use List?
Use List when:
β You need to add or remove items
β You need index access
β You need to modify collection
Example:
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(20);
numbers[0] = 50;
Real-Life Example
Imagine a Library:
IEnumerable β You can only read books.
List β You can add, remove, or edit books.
β‘ Performance Difference :
In real projects, we often return IEnumerable from methods to make code flexible.
π Conclusion
In this article, we learned:
What is IEnumerable
What is List
Key differences
When to use each
Example with output
Interview tips
If you are beginner:
β Use List when modifying data
β Use IEnumerable when reading data