You 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:
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
In this example, a List<string> named names is created and populated with the provided values "Alice," "Bob," and "Charlie."
This code initializes a HashSet<int> called uniqueNumbers with the values 5, 10, 15, and 20.
Array Initialization (in C# 6.0 and later):
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You 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.