07 Feb 2024
IEnumerable
, ICollection
, IList
, and IDictionary
are interfaces in the .NET framework that provide different levels of functionality for working with collections of objects.
IEnumerable<T>
:
IEnumerable<T>
is the most basic interface for .NET collections. It represents a forward-only cursor for a collection, enabling you to iterate over a collection of a specific type. It provides a single method, GetEnumerator()
, which returns an IEnumerator<T>
that allows you to iterate through the collection.
Uses:
- Iterating over collections using
foreach
loops. - LINQ queries - LINQ extends
IEnumerable<T>
to provide powerful querying capabilities over collections.
Example:
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
Console.WriteLine(number);
}
ICollection<T>
:
ICollection<T>
extends IEnumerable<T>
and adds methods to add, remove, and check for the presence of elements in the collection. It represents a generic collection of objects and is more feature-rich than IEnumerable<T>
.
Uses:
- Adding and removing elements from a collection.
- Checking the count of elements in a collection.
Example:
ICollection<string> names = new List<string>();
names.Add("John");
names.Add("Jane");
names.Remove("John");
Console.WriteLine($"Count: {names.Count}");
IList<T>
:
IList<T>
extends ICollection<T>
and adds methods to access and modify elements by index. It represents a non-generic list of objects that can be accessed by index.
Uses:
- Accessing and modifying elements by index.
- Performing operations like sorting, searching, and inserting elements at specific positions.
Example:
IList<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[2]); // Output: 3
numbers.Insert(2, 10);
Console.WriteLine(string.Join(", ", numbers)); // Output: 1, 2, 10, 3, 4, 5
IDictionary<TKey, TValue>
:
IDictionary<TKey, TValue>
represents a generic collection of key-value pairs. It provides methods to add, remove, and search for elements by key.
Uses:
- Associating unique keys with values for efficient retrieval.
- Performing dictionary-style operations like adding, removing, and updating key-value pairs.
Example:
IDictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 30);
ages.Add("Jane", 25);
ages["John"] = 32;
Console.WriteLine($"John's age: {ages["John"]}");
These interfaces provide common patterns for handling collections in .NET and are fundamental to understanding and working with collections effectively in C#.