No history yet

Introduction to C# Lists

Beyond Fixed Arrays

In programming, you often need to store a group of related items. You've likely used arrays for this, which are great for holding a fixed number of elements. But what if you don't know how many items you'll need? If you create an array for 10 items but end up with 11, you're stuck. If you create space for 100 but only use 5, you've wasted memory.

This is where lists come in. A list in C# is a dynamic collection, meaning it can grow or shrink as you add or remove items. Think of it like a shopping list on your phone versus a pre-printed one. You can add new items or delete ones you've found without needing a whole new piece of paper.

The main advantage of a list over an array is flexibility. Lists automatically manage their own size, so you don't have to.

Creating Your First List

To use lists in C#, you'll work with the List<T> class. This class lives in a part of the .NET library called the System.Collections.Generic namespace. To get access to it, you'll usually add using System.Collections.Generic; at the top of your code file.

The <T> in List<T> is a placeholder for a type. This is a concept called generics. It means you can create a list of anything by specifying the data type inside the angle brackets. You can have a list of integers (List<int>), a list of strings (List<string>), or even a list of more complex objects.

// First, ensure you have access to the List class
using System.Collections.Generic;

// Declare and initialize an empty list of integers
List<int> highScores = new List<int>();

// Declare and initialize an empty list of strings
List<string> playerNames = new List<string>();

In the code above, we declare a variable (like highScores) and then use new List<int>() to create an actual, empty list instance in memory. This gives us a ready-to-use list that can start holding integers.

You can also create a list and populate it with some initial values right away. This is useful when you already know a few items that need to be in the collection from the start.

// Initialize a list of integers with starting values
List<int> startingLevels = new List<int> { 1, 5, 10, 20 };

// Initialize a list of strings with starting values
List<string> questItems = new List<string> { "Key", "Map", "Compass" };

This syntax uses curly braces {} to enclose a comma-separated list of elements. The list is automatically sized to hold these initial items, and you're free to add or remove more later on.

Quiz Questions 1/4

What is the primary advantage of using a List<T> over a standard array in C#?

Quiz Questions 2/4

Which using directive is required at the top of a C# file to gain access to the List<T> class?