How To Create A List In C#?

To create a List in C#, you can use the List<T> class, where T is the type of item you want to store in the list. Here's an example of how to create a List of integers:

List<int> numbers = new List<int>();

This creates an empty List of integers named numbers.

To add items to the list, you can use the Add method:

numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

This adds the integers 1, 2, and 3 to the numbers List.

You can also create a List and add items to it in a single statement using collection initializer syntax:

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

This creates a List of strings named names and initializes it with the values "Alice", "Bob", and "Charlie".

To access items in the List, you can use the index operator ([]):

int firstNumber = numbers[0];
string firstName = names[0];

This retrieves the first item in the numbers List (which is 1) and the names List (which is "Alice").

You can also use a foreach loop to iterate over all the items in the List:

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

This prints the numbers 1, 2, and 3 to the console.

These are some basic examples of how to create and use a List in C#

You can also create a list of objects. Here is a detailed article on How To Create A List Of Objects In C#?

Next reading: C# List Tutorial - Everything You Need To Learn About List In C# (c-sharpcorner.com)


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.