Collection Initializers
In this page:
Collection Initializers
Collection initializer syntax lets you populate an array, list, or dictionary immediately at creation with { ... }, without a separate series of .Add() calls. It works for any type implementing IEnumerable that has an Add method. This makes setup code much more compact and readable.
Note: Object and collection initializers combine well — you can initialize a list of custom objects in one expression.
Example: Collection Initializers
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3 };
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Al", 10 },
{ "Bo", 20 },
};
Console.WriteLine(numbers.Count);
Console.WriteLine(scores["Bo"]);
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: