How to create and populate a collection in a single statement?
How to create and populate a collection in a single statement?
16403-Nov-2023
Updated on 05-Nov-2023
Home / DeveloperSection / Forums / How to create and populate a collection in a single statement?
How to create and populate a collection in a single statement?
Aryan Kumar
05-Nov-2023You can create and populate a collection in a single statement using collection initializer syntax available in C#. This syntax is a convenient way to initialize and populate collections like lists, dictionaries, and sets. Here's how to do it:
List Initialization:
In this example, a List<string> named names is created and populated with the provided values "Alice," "Bob," and "Charlie."
Dictionary Initialization:
Here, a Dictionary<int, string> named ageMap is created and populated with key-value pairs.
Set Initialization (using HashSet):
This code initializes a HashSet<int> called uniqueNumbers with the values 5, 10, 15, and 20.
Array Initialization (in C# 6.0 and later):
While not a collection in the traditional sense, you can also use collection initializer syntax to create and populate arrays.
The key to using collection initializer syntax is to enclose the initial values within curly braces {} and provide the values separated by commas. The compiler will take care of creating and populating the collection. This syntax makes code more concise and readable, especially when initializing collections with initial values.