C#
List<T> basics
Learn to create dynamic arrays with List<T> and call Add.
List<T> basics
List<T> is a dynamically sized collection. Unlike regular arrays in C#, the element count is not fixed; it grows as you add items and shrinks as you remove them.
To declare one, write new List<int>(); the T inside the angle brackets is the element type. To add an item, call the Add method: nums.Add(10);. Example: List<string> names = new List<string>(); names.Add("Ayşe");.
Count and collection initializer
The Count property gives the number of items in the list. It returns 0 for an empty list and increases by one with each Add.
To give items at declaration, use a collection initializer: List<int> nums = new List<int>() { 1, 2, 3 };. The values inside the braces are added in order; it is shorter than writing separate Add calls.
Exercise Add three numbers to a list
Declare an empty list with List<int> nums = new List<int>();. Then add the values 5, 10 and 15 in order using Add. Finally print nums.Count with Console.WriteLine.
Show example solution
First declare with List<int> nums = new List<int>();, call nums.Add(...) three times, then print with Console.WriteLine(nums.Count);.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare an empty int list, add three numbers and print the count
List<int> nums = new List<int>();
nums.Add(5);
nums.Add(10);
nums.Add(15);
Console.WriteLine(nums.Count);
}
}
Test yourself
-
What does nums.Count print after two Add calls?
List<int> nums = new List<int>();
nums.Add(10);
nums.Add(20);
Console.WriteLine(nums.Count);
Show answer
2 — Correct. Two items were added; the Count property returns 2.
-
Add call
List<int> nums = new List<int>();
____
Console.WriteLine(nums.Count);
Show answer
List<int> nums = new List<int>();
nums.Add(15);
Console.WriteLine(nums.Count);
-
Match each expression to its meaning
- new List<int>()
- Empty list
- nums.Add(5)
- Adds an item
- nums.Count
- Item count
- List<string>
- Text list
Next lesson: List<T> methods