What is the List.Add() method in C#?
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.
Syntax
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.
Code example
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);}}}
Explanation
Lines 1–2: Uses directives that allow us to use classes and functionality from the
Systemnamespace and theSystem.Collections.Genericnamespace, 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 thecolorslist.Lines 15–18: This is a
foreachloop that iterates through each element (string c) in thecolorslist and prints each color to the console.
Free Resources