How to initialize a List<T> in C#
In this tutorial, you will learn how to initialize a list in C#. We will show you examples of creating an empty list and a list with initial values.
See also:
Initialize a list in C#
Creating an empty list
To create a new empty list, you can write as follows:
List<DataType> variable name = new List<DataType>();
Example:
List<int> numbers = new List<int>();
Before you can use the List<T> class, you need to declare the following namespace:
using System.Collections.Generic;
Initializing a list
To initialize a new list with values, you can write as follows:
List<DataType> variable name = new List<DataType>() { value1, value2, value3, value4, };
Example:
List<int> numbers = new List<int>() {1, 2, 3, 4, 5, 6};
Examples of C# List<T> initialization
The following sample program is an example of List<T> initialization in C#:
using System; using System.Collections.Generic; namespace CSharp_List_Initialization { public class Program { public static void Main(string[] args) { //Create an empty list List<int> list = new List<int>(); Console.WriteLine("The number of elements: {0}", list.Count); //Add items to the list list.Add(1); list.Add(3); list.Add(2); list.Add(4); list.Add(5); Console.WriteLine("The number of elements: {0}", list.Count); //Print elements of the list Console.WriteLine("{0}", string.Join(",", list)); } } }
Output:
The number of elements: 0
The number of elements: 5
1,3,2,4,5
The following sample program shows how to initialize a list:
using System; using System.Collections.Generic; namespace CSharp_List_Initialization { public class Program { public static void Main(string[] args) { //Create an empty list List<int> list = new List<int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("The number of elements: {0}", list.Count); //Print elements of the list Console.WriteLine("{0}", string.Join(",", list)); //Add items to the list list.Add(6); list.Add(7); list.Add(8); list.Add(9); list.Add(10); Console.WriteLine("The number of elements: {0}", list.Count); //Print elements of the list Console.WriteLine("{0}", string.Join(",", list)); //Remove list.Remove(6); list.Remove(7); Console.WriteLine("The number of elements: {0}", list.Count); //Print elements of the list Console.WriteLine("{0}", string.Join(",", list)); } } }
Output
The number of elements: 5
1,2,3,4,5
The number of elements: 10
1,2,3,4,5,6,7,8,9,10
The number of elements: 8
1,2,3,4,5,8,9,10
Summary
In this tutorial, you learned how to initialize a list in C#. There are two ways to create a list: an empty list or a list with initial values.