How to create a list in C#

Share

A list is a collection of elements of the same data type that provides functionalities like indexing, searching, sorting, and manipulating list elements.

The List<T> class is defined in the System.Collections.Generic namespace. It is a generic class and can store elements of ​any data type.

svg viewer

Syntax

Have a look at the syntax used to call the List<T> constructor to create a list:

List<T> my_list = new List<T>();

T can be any data type (e.g., string, int, etc.)

Code

The code snippet below illustrates the process of creating a list in C#:

using System.Collections.Generic;
class HelloWorld
{
static void Main()
{
// Creating a list of strings
List<string> Fruits = new List<string>();
// Adding elements to the Fruits list
Fruits.Add("Apple");
Fruits.Add("Banana");
Fruits.Add("Mango");
// Printing the list
Fruits.ForEach(System.Console.WriteLine);
}
}

Explanation

  • Line 1: This line includes the namespace System.Collections.Generic, which contains the generic collection classes such as List<T>

  • Line 8: This line declares a new variable named Fruits of type List<string>. List<string> is a generic collection class that can store a sequence of strings. The new List<string>() part creates a new instance of the List<string> class and assigns it to the Fruits variable.

  • Lines 11–13: These lines add the string "Apple/Banana/Mango" to the Fruits list. The add method is a member of the List<T> class and is used to add elements to the end of the list.

  • Line 16: This line uses the ForEach method of the List<T> class to iterate over each element in the Fruits list and perform an action on each element. The action specified here is System.Console.WriteLine, which is a method that prints the element to the console. 

Copyright ©2024 Educative, Inc. All rights reserved