EN
C# / .NET - create List with values initialized on creation
0
points
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