MSDN Documentation

.NET Framework Collections

Introduction to Collections in .NET Framework

Collections in the .NET Framework provide a way to store, retrieve, and manipulate groups of objects. They are fundamental to many programming tasks, offering flexible and efficient ways to manage data. The System.Collections and System.Collections.Generic namespaces contain a rich set of collection types.

Why Use Collections?

Key Concepts

Non-Generic Collections

These collections, found in the System.Collections namespace, store elements as objects. This means you need to cast elements to their specific types when retrieving them, which can lead to runtime errors and reduced performance.

Examples include:

While historically important, non-generic collections are generally discouraged in favor of generic collections for type safety and performance.

Generic Collections

Introduced with .NET Framework 2.0, generic collections reside in the System.Collections.Generic namespace. They allow you to specify the type of elements the collection can hold at compile time. This eliminates the need for casting and provides strong type checking, preventing runtime type errors and improving performance.

Examples include:

The use of generics is highly recommended for new development.

Common Collection Interfaces

The .NET Framework defines several interfaces that collection types implement. Understanding these interfaces is crucial for writing flexible and adaptable code.

Example Usage (Generic List)

Here's a simple example demonstrating the use of List<string>:

                
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        // Create a generic list of strings
        List<string> fruits = new List<string>();

        // Add elements to the list
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Orange");

        // Access elements by index
        Console.WriteLine($"First fruit: {fruits[0]}"); // Output: First fruit: Apple

        // Iterate through the list
        Console.WriteLine("\nAll fruits:");
        foreach (string fruit in fruits)
        {
            Console.WriteLine($"- {fruit}");
        }

        // Check if an element exists
        if (fruits.Contains("Banana"))
        {
            Console.WriteLine("\nBanana is in the list.");
        }

        // Remove an element
        fruits.Remove("Orange");

        Console.WriteLine($"\nList count after removal: {fruits.Count}");
    }
}
                
            

This introduction covers the fundamental aspects of collections in the .NET Framework. Continue to the next sections to explore generic and non-generic collections in more detail, along with their specific interfaces and advanced usage patterns.