C# List add elements example

In this source code example, we will demonstrate how to add elements to List in C#.

The Add method adds an element at the end of the list. The AddRange method adds the elements of the specified collection to the end of the list.

C# List add elements example

The following example creates a new list and adds new elements to it.
using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var fruits = new List<string> { "banana", "mango", "apple", "watermelon" };
        
        fruits.Add("orange");
        fruits.Add("pear");
        
        var fruits2 = new string[] { "grapes", "blackberry" };
        fruits.AddRange(fruits2);
        
        fruits.ForEach(Console.WriteLine);
    }
}

Output:

banana
mango
apple
watermelon
orange
pear
grapes
blackberry
With AddRange method, we add another collection to the list:
        var fruits2 = new string[] { "grapes", "blackberry" };
        fruits.AddRange(fruits2);

Related C# List Examples


Comments