Namespace System.Collections.Generic
Provides interfaces and classes that define generic collections, which allow developers to create strongly typed collections that improve performance and reduce the chances of runtime errors.
Generic collections are type-safe. This means that a collection can hold only elements of a specific type. For example, a List<int> can hold only integers. If you attempt to add an object of a different type to the list, you will get a compile-time error. This eliminates the need for casting, which can be a performance bottleneck and a source of runtime errors.
The System.Collections.Generic namespace contains the following:
- Interfaces: These define the contracts for various collection types.
- Classes: These are concrete implementations of the interfaces, providing ready-to-use collection data structures.
Classes
Represents a strongly typed list of objects that can be accessed by index. Provides methods for manipulating lists, such as adding, removing, and searching for elements.
Represents a collection of key/value pairs that are sorted by key. Provides efficient lookup of values by their keys.
Represents a set of values of the same type. Sets are unordered collections that do not allow duplicate elements.
Represents a first-in, first-out (FIFO) collection of objects. Elements are added to the end of the queue and removed from the beginning.
Represents a last-in, first-out (LIFO) collection of objects. Elements are added to the top of the stack and removed from the top.
Interfaces
Exposes an enumerator, which supports a simple iteration over a collection of a specific type.
Represents a strongly typed collection of objects that can be accessed by index. Inherits from IEnumerable<T>.
Represents a collection of objects that can be individually accessed by the index. Inherits from ICollection<T>.
Represents a collection of key/value pairs. Inherits from ICollection<KeyValuePair<TKey, TValue>>.
Example Usage
Here's a simple example of using List<T> to store strings:
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
// Create a list of strings
List<string> names = new List<string>();
// Add elements to the list
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
// Access elements by index
Console.WriteLine($"First name: {names[0]}"); // Output: First name: Alice
// Iterate over the list
Console.WriteLine("All names:");
foreach (string name in names)
{
Console.WriteLine($"- {name}");
}
// Remove an element
names.Remove("Bob");
Console.WriteLine($"\nAfter removing Bob, the list contains {names.Count} names.");
}
}