Introduction
Collection initialization syntax helps you quickly create and fill a collection with items in one simple step.
Jump into concepts and practice - no test required
var collection = new CollectionType { item1, item2, item3 };var numbers = new List<int> { 1, 2, 3, 4 };
var names = new HashSet<string> { "Alice", "Bob", "Charlie" };
var dict = new Dictionary<int, string> { {1, "One"}, {2, "Two"} };
using System; using System.Collections.Generic; class Program { static void Main() { var fruits = new List<string> { "Apple", "Banana", "Cherry" }; foreach (var fruit in fruits) { Console.WriteLine(fruit); } } }
var list = new List<int> { 1, 2, 3 };new List<int> { 1, 2, 3 } creates a list and fills it with 1, 2, and 3 immediately.{ {key, value}, ... }.var set = new HashSet<int> { 1, 2, 2, 3 };
Console.WriteLine(set.Count);var list = new List<int> { 1, 2, "3" };