The List.Add()
method in C# adds an object to the end of a List<T>
collection. A List<T>
is a generic collection that can store elements of any type T
. For example, we can create a List<string>
to store strings or a List<int>
to store integers.
The syntax of the List.Add()
method is given below:
List<T>.Add(T item);
Here, T
is the type of the element we want to add, and item
is the object we want to add. For example, if we have a List<string>
called names
, we can add strings to it by using: names.Add("John")
, names.Add("Alice")
and so on.
Let’s see how the List.Add()
method works:
using System;using System.Collections.Generic;class Test{static void Main(){List<string> colors = new List<string>();colors.Add("Red");colors.Add("Blue");colors.Add("Orange");colors.Add("Purple");foreach (string c in colors){Console.WriteLine(c);}}}
Lines 1–2: Uses directives that allow us to use classes and functionality from the System
namespace and the System.Collections.Generic
namespace, respectively.
Line 8: Declares a generic list of strings named colors
. It is an empty list at this point.
Lines 10–13: Adds four strings ("Red"
, "Blue"
, "Orange"
, "Purple"
) to the colors
list.
Lines 15–18: This is a foreach
loop that iterates through each element (string c
) in the colors
list and prints each color to the console.
Free Resources