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:
xxxxxxxxxx
1
List<string> myList1 = new List<string> { "item1", "item2", "item3" };
2
3
List<int> myList2 = new List<int> { 1, 2, 3 };
In this example, we create two list with values initialized on their creation.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class TestClass
5
{
6
public static void Main()
7
{
8
List<string> myList1 = new List<string> { "item1", "item2", "item3" };
9
10
foreach (string item in myList1)
11
{
12
Console.WriteLine(item);
13
}
14
15
List<int> myList2 = new List<int> { 1, 2, 3 };
16
17
foreach (int item in myList2)
18
{
19
Console.WriteLine(item);
20
}
21
}
22
}
Output:
xxxxxxxxxx
1
item1
2
item2
3
item3
4
1
5
2
6
3