C# List

The C# List<T> class is employed for storing and retrieving elements, allowing for duplicates. This class is located within the System.Collections.Generic namespace.

C# List__PRESERVE_6__ example

Let's examine a sample of a generic ArrayList class that stores elements through the Add method and traverses the list using a for-each loop.

Example

using System;

using System.Collections.Generic;



public class ListExample

{

    public static void Main(string[] args)

    {

        // Create a list of strings

        var names = new List<string>();

        names.Add("Sonoo Jaiswal");

        names.Add("Ankit");

        names.Add("Peter");

        names.Add("Irfan");



        // Iterate list element using foreach loop

        foreach (var name in names)

        {

            Console.WriteLine(name);

        }

    }

}

Output:

Output

Sonoo Jaiswal

Ankit

Peter

Irfan

C# List__PRESERVE_8__ example using collection initializer

Example

using System;

using System.Collections.Generic;



public class ListExample

{

    public static void Main(string[] args)

    {

        // Create a list of strings using collection initializer

        var names = new List<string>() {"Sonoo", "Vimal", "Ratan", "Love" };

       

        // Iterate through the list.

        foreach (var name in names)

        {

            Console.WriteLine(name);

        }

    }

}

Output:

Output

Sonoo

Vimal

Ratan

Love

Input Required

This code uses input(). Please provide values below: