0
0
C Sharp (C#)programming~5 mins

Collection initialization syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Collection initialization syntax helps you quickly create and fill a collection with items in one simple step.
When you want to create a list of names to store in memory.
When you need to prepare a set of values before saving them to a database.
When you want to test database queries with sample data.
When you want to group related items together for easy access.
When you want to avoid writing multiple lines to add items one by one.
Syntax
C Sharp (C#)
var collection = new CollectionType { item1, item2, item3 };
You can use this syntax with lists, arrays, dictionaries, and other collections.
Each item inside the braces is added to the collection automatically.
Examples
Creates a list of integers with four numbers.
C Sharp (C#)
var numbers = new List<int> { 1, 2, 3, 4 };
Creates a set of unique names.
C Sharp (C#)
var names = new HashSet<string> { "Alice", "Bob", "Charlie" };
Creates a dictionary with key-value pairs.
C Sharp (C#)
var dict = new Dictionary<int, string> { {1, "One"}, {2, "Two"} };
Sample Program
This program creates a list of fruits using collection initialization and prints each fruit.
C Sharp (C#)
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);
        }
    }
}
OutputSuccess
Important Notes
Collection initialization makes code shorter and easier to read.
For dictionaries, use curly braces inside the main braces to add key-value pairs.
You can mix collection initialization with other collection methods if needed.
Summary
Collection initialization lets you create and fill collections in one step.
It works with many collection types like lists, sets, and dictionaries.
This syntax makes your code cleaner and easier to understand.