Languages
[Edit]
EN

C# / .NET - create List with values initialized on creation

0 points
Created by:
Veer-Ahmad
487

In this article, we would like to show you how to create List with values initialized on creation in C#.

Quick solution:

List<string> myList1 = new List<string> { "item1", "item2", "item3" };

List<int> myList2 = new List<int> { 1, 2, 3 };

 

Practical example

In this example, we create two list with values initialized on their creation.

using System;
using System.Collections.Generic;

public class TestClass
{
    public static void Main()
    {
        List<string> myList1 = new List<string> { "item1", "item2", "item3" };

        foreach (string item in myList1)
        {
            Console.WriteLine(item);
        }

        List<int> myList2 = new List<int> { 1, 2, 3 };

        foreach (int item in myList2)
        {
            Console.WriteLine(item);
        }
    }
}

Output:

item1
item2
item3
1
2
3
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join