Lists: Dynamic Arrays for Flexible Data Storage

Lists in C# provide a dynamic and flexible way to store collections of data. Unlike arrays, which have a fixed size determined at the time of declaration, lists can grow or shrink as needed, making them ideal for situations where the number of elements is not known in advance or changes frequently. This dynamic nature simplifies many programming tasks and reduces the need for manual memory management.

Understanding Lists

List<T> in C# is a generic collection, meaning it can hold elements of a specific type, denoted by T. This type safety ensures that you only store and retrieve elements of the correct type, preventing runtime errors. The List<T> class is part of the System.Collections.Generic namespace, so you'll need to include this namespace in your code using using System.Collections.Generic;.

Key Characteristics of Lists

Creating and Initializing Lists

You can create a list using the new keyword followed by the List<T> constructor. Here are several ways to initialize a list:

  1. Empty List:

    using System.Collections.Generic;
    
    List<int> numbers = new List<int>(); // Creates an empty list of integers
    List<string> names = new List<string>(); // Creates an empty list of strings
    
  2. List with Initial Capacity:

    List<int> numbers = new List<int>(10); // Creates a list of integers with an initial capacity of 10
    

    Note: Specifying an initial capacity can improve performance if you have an estimate of the number of elements the list will hold, as it reduces the number of times the list needs to resize its internal array.

  3. List with Initial Elements (Collection Initializer):

    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 }; // Creates a list with initial elements
    List<string> names = new List<string>() { "Alice", "Bob", "Charlie" }; // Creates a list with initial elements
    
  4. List from an Existing Collection:

    int[] array = { 1, 2, 3 };
    List<int> numbers = new List<int>(array); // Creates a list from an existing array
    
    List<string> moreNames = new List<string>(names); // Creates a list from another list
    

Adding Elements to a List

Lists provide several methods for adding elements:

Add()

The Add() method appends an element to the end of the list.