System.Collections.Generic Namespace
This namespace provides interfaces and classes that define generic collections, which allow programmers to create collections of objects that are strongly typed, perform better, and are safer than non-generic collections.
Generic collections are implemented in the .NET Framework and are available in the System.Collections.Generic namespace.
Key Concepts
- Generics: Allow you to define a collection that works with any type of data, rather than a specific type. This reduces code duplication and improves type safety.
- Type Safety: When you create a generic collection, you specify the type of elements it will hold. This prevents you from adding elements of the wrong type, reducing runtime errors.
- Performance: Generic collections often perform better than their non-generic counterparts because they avoid the boxing and unboxing operations that are required for value types when stored in non-generic collections.
Commonly Used Generic Collections
List<T>
Represents a list of objects that can be accessed by index. It is a resizable array.
Dictionary<TKey, TValue>
Represents a collection of key/value pairs that are sorted by key. It provides efficient lookups based on the key.
HashSet<T>
Represents a set of values. A set is a collection that contains no duplicate elements and has no defined order.
Queue<T>
Represents a first-in, first-out (FIFO) collection of objects. Elements are added to the end and removed from the beginning.
Stack<T>
Represents a last-in, first-out (LIFO) collection of objects. Elements are added to the end and removed from the beginning.
LinkedList<T>
Represents a doubly linked list. It provides O(1) time complexity for adding or removing elements at any point in the list.
Interfaces
The System.Collections.Generic namespace also defines a set of powerful interfaces that form the foundation for all generic collection types:
IEnumerable<out T>: Exposes an enumerator, which supports a simple iteration over a collection of a specific type.ICollection<T>: Represents a strongly typed collection of objects.IList<T>: Represents a strongly typed list of objects that can be accessed by index.IDictionary<TKey, TValue>: Represents a collection of key/value pairs.