C# List
The List<T>
class in C# is a generic class that is part of the System.Collections.Generic
namespace. It provides a dynamic, resizable array that can hold elements of any data type T
. The List<T>
class is one of the most commonly used collection classes in C#.
Here is an example of how to create a List<int>
and add some elements to it:
using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); Console.WriteLine(numbers[0]); // Output: 1 Console.WriteLine(numbers[1]); // Output: 2 Console.WriteLine(numbers[2]); // Output: 3 } }
In this example, we first create a new List<int>
object called numbers
. We then add three integers to the list using the Add
method. Finally, we use the index operator ([]
) to access and print the elements of the list.
The List<T>
class provides many other useful methods for working with lists, such as Insert
, Remove
, Sort
, Contains
, and more. It also supports properties like Count
, which returns the number of elements in the list, and Capacity
, which returns the current capacity of the list.
One advantage of using a List<T>
over an array is that you can easily add or remove elements from the list without having to manually resize the underlying data structure. The List<T>
class will automatically resize the internal array as needed to accommodate the new elements.