Arrays are great, but they have one big limitation โ their size is fixed. What if you
do not know how many items you will need? That is where List comes in. It is
like an array that can grow and shrink dynamically.
Creating a List
List<string> names = new List<string>();
List<int> scores = new List<int> { 85, 92, 78, 95 };
The angle brackets <string> tell C# what type of data the list will hold.
This is called a generic type. You can create lists of any type โ strings,
integers, custom objects, anything.
Adding and Removing Items
List<string> cities = new List<string>();
cities.Add("Kano");
cities.Add("Lagos");
cities.Add("Abuja");
Console.WriteLine(cities.Count); // 3
cities.Insert(1, "Ibadan"); // Insert at index 1
// cities: Kano, Ibadan, Lagos, Abuja
cities.Remove("Lagos"); // Remove by value
cities.RemoveAt(0); // Remove by index
// cities: Ibadan, Abuja
cities.Clear(); // Remove everything
See how easy it is? With arrays, you would have to create a new array and copy everything
over. With List, it handles all of that behind the scenes.
Accessing and Searching
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers[0]); // 10
Console.WriteLine(numbers.Count); // 5
int index = numbers.IndexOf(30); // 2
bool has40 = numbers.Contains(40); // true
numbers.Sort();
numbers.Reverse();
List has all the useful methods you would expect โ IndexOf,
Contains, Sort, Reverse, and more.
Looping Through a List
List<string> students = new List<string>
{
"Amina", "Bilal", "Chukwuemeka", "Fatima"
};
// Using foreach
foreach (string student in students)
{
Console.WriteLine(student);
}
// Using for (when you need the index)
for (int i = 0; i < students.Count; i++)
{
Console.WriteLine($"{i + 1}. {students[i]}");
}
List vs Array
- Use Array when you know the exact size and it will not change
- Use List when you need to add or remove items dynamically
- Arrays are slightly faster, but the difference is negligible for most applications
In practice, you will use List much more often than arrays. It is more
flexible and easier to work with.