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.

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.");
    }
}