How to create a list in C#
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.
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 stringsList<string> Fruits = new List<string>();// Adding elements to the Fruits listFruits.Add("Apple");Fruits.Add("Banana");Fruits.Add("Mango");// Printing the listFruits.ForEach(System.Console.WriteLine);}}
Explanation
Line 1: This line includes the namespace
System.Collections.Generic, which contains the generic collection classes such asList<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 newList<string>()part creates a new instance of theList<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
ForEachmethod of theList<T>class to iterate over each element in the Fruits list and perform an action on each element. The action specified here isSystem.Console.WriteLine, which is a method that prints the element to the console.
Free Resources