Collection Interfaces in C#
What are Collection Interfaces in C#?
The Collection Interfaces in C# define standard behaviors for collections, such as adding, removing, and accessing elements. These interfaces are implemented by various collection classes in the System.Collections and System.Collections.Generic namespaces.
Key Features of Collection Interfaces
- Provides a common contract for different collection types.
- Supports type safety and flexibility.
- Improves code reusability and maintainability.
- Includes generic (
ICollection<T>) and non-generic (ICollection) versions.
Common Collection Interfaces in C#
Below are some commonly used collection interfaces and their functionalities:
| Interface | Description | Implemented By |
|---|---|---|
IEnumerable |
Supports iteration over a collection. | List<T>, Array, Dictionary<TKey, TValue> |
ICollection |
Defines size, enumeration, and synchronization methods. | List<T>, Dictionary<TKey, TValue> |
IList |
Supports indexed access and element manipulation. | List<T>, ArrayList |
IDictionary |
Stores key-value pairs. | Dictionary<TKey, TValue>, SortedList<TKey, TValue> |
ISet |
Represents a collection of unique elements. | HashSet<T>, SortedSet<T> |
Example: Implementing IEnumerable
The IEnumerable interface allows iteration over a collection.
Example: Custom Collection Implementing IEnumerable
using System;
using System.Collections;
using System.Collections.Generic;
class MyCollection : IEnumerable
{
private int[] numbers = { 1, 2, 3, 4, 5 };
public IEnumerator GetEnumerator()
{
foreach (int number in numbers)
{
yield return number;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// Usage
class Program
{
static void Main()
{
MyCollection collection = new MyCollection();
foreach (var num in collection)
{
Console.WriteLine(num);
}
}
}
// Output:
// 1
// 2
// 3
// 4
// 5
The MyCollection class implements IEnumerable<T>, allowing iteration using a foreach loop.
Example: Using IDictionary
The IDictionary interface represents a collection of key-value pairs.
Example: Implementing IDictionary
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
IDictionary students = new Dictionary();
students.Add(1, "Alice");
students.Add(2, "Bob");
students.Add(3, "Charlie");
Console.WriteLine("Students List:");
foreach (var pair in students)
{
Console.WriteLine($"ID: {pair.Key}, Name: {pair.Value}");
}
}
}
// Output:
// Students List:
// ID: 1, Name: Alice
// ID: 2, Name: Bob
// ID: 3, Name: Charlie
The Dictionary class implements IDictionary, providing fast key-value pair lookups.
Best Practices for Using Collection Interfaces
- Use
IEnumerablefor read-only iteration over a collection. - Use
ICollectionfor adding, removing, and counting elements. - Use
IListwhen random access by index is required. - Use
IDictionarywhen working with key-value pairs. - Use
ISetto ensure unique elements in a collection.