Creating and initializing collections is something C# developers do almost every day. Whether you are working with arrays, lists, dictionaries, or other collection types, initializing them is a regular part of application development.

Traditionally, C# developers use different syntax depending on the collection type. Arrays use array initializers, lists use collection initializers, and other collection types may require factory methods or constructors.

Although these approaches work well, they can make everyday code unnecessarily verbose, especially when a method needs to combine multiple collections or initialize a collection with a few values.

Collection expressions provide a simpler way to create collections using square brackets. They allow developers to initialize different collection types with a consistent syntax and reduce unnecessary code.

Introduced in C# 12, collection expressions also support spread elements, which make it easier to combine existing collections without writing additional loops.

In this article, we will explore how collection expressions work, understand their practical applications, and see how they can make everyday C# code cleaner and easier to maintain.

Understanding Collection Expressions in C#

A collection expression is a simplified syntax for creating collection values. Instead of writing the collection type followed by an initializer, developers can use square brackets to define the elements.

Consider the traditional approach to creating an array:

C#
int[] numbers = new int[] { 10, 20, 30, 40 };

Using a collection expression, the same code becomes:

C#
int[] numbers = [10, 20, 30, 40];

The result is the same, but the second approach requires less syntax.

Collection expressions are not limited to arrays. They can also initialize lists, spans, and several collection interfaces.

For example:

C#
int[] numbers = [10, 20, 30];

List<string> names = ["John", "David", "Sarah"];

Span<int> scores = [85, 90, 95, 100];

IEnumerable<string> technologies =
    ["C#", "ASP.NET Core", "SQL"];

The important difference is that the target type determines which collection is created.

This feature makes collection initialization more consistent across different parts of an application.

Creating Arrays and Lists With Collection Expressions

Arrays and lists are among the most frequently used collection types in C#.

Before collection expressions, developers generally used different initialization syntax for these types.

Consider the following examples:

C#
// Traditional array initialization
int[] numbers = new int[] { 1, 2, 3, 4 };

// Traditional list initialization
List<string> languages = new List<string>
{
    "C#",
    "Java",
    "Python"
};

With collection expressions, both can use the same syntax:

C#
int[] numbers = [1, 2, 3, 4];

List<string> languages = ["C#", "Java", "Python"];

This is particularly useful when initializing configuration values, application settings, supported file extensions, or predefined business rules.

For example, an application may support a fixed set of file extensions:

C#
public static class FileSettings
{
    public static readonly string[] AllowedExtensions =
    [
        ".pdf",
        ".docx",
        ".xlsx",
        ".csv"
    ];
}

The collection is easy to read and update without introducing unnecessary initialization code.

Using Empty Collection Expressions

One common requirement in application development is returning an empty collection when no records are available.

Traditionally, developers might write:

C#
List<string> messages = new List<string>();

int[] numbers = Array.Empty<int>();

Collection expressions provide a consistent alternative:

C#
List<string> messages = [];

int[] numbers = [];

IEnumerable<int> values = [];

The compiler determines the collection type from the target.

For an empty array, the compiler can use an optimized empty array instance where appropriate. However, the actual implementation depends on the target type and how the resulting collection is used.

There is one important restriction: collection expressions require a target type.

The following code does not compile:

C#
var numbers = [10, 20, 30];

The compiler cannot determine the intended collection type from the collection expression alone.

Instead, provide an explicit type:

C#
int[] numbers = [10, 20, 30];

Or use an explicitly typed variable declaration:

C#
List<int> numbers = [10, 20, 30];

Understanding target typing is important when using collection expressions in everyday development.

Combining Collections Using Spread Elements

One of the most useful features of collection expressions is the spread element.

The spread operator uses two consecutive dots (..) to include elements from an existing collection.

Consider an application that maintains separate collections for active and inactive users.

Using the traditional approach:

C#
List<string> activeUsers =
    new() { "John", "Sarah" };

List<string> inactiveUsers =
    new() { "David", "Michael" };

List<string> allUsers = new(activeUsers);

allUsers.AddRange(inactiveUsers);

With collection expressions, the same operation becomes:

C#
List<string> activeUsers =
    ["John", "Sarah"];

List<string> inactiveUsers =
    ["David", "Michael"];

List<string> allUsers =
    [.. activeUsers, .. inactiveUsers];

The spread elements include all items from the existing collections.

You can also combine individual values with existing collections:

C#
int[] firstBatch = [10, 20, 30];

int[] secondBatch = [40, 50, 60];

int[] allNumbers =
    [0, .. firstBatch, .. secondBatch, 70];

The resulting collection contains:

Code
0, 10, 20, 30, 40, 50, 60, 70

This approach is useful when combining application settings, merging predefined values, or creating a new collection from multiple sources.

Keep in mind that spreading a collection enumerates its elements to build the resulting collection. It does not create a lazy sequence like an unevaluated LINQ query.

Using Collection Expressions With Method Parameters

Collection expressions are also useful when passing collections directly to methods.

Consider a method that calculates the total of a set of numbers:

C#
public static int CalculateTotal(IEnumerable<int> numbers)
{
    return numbers.Sum();
}

You can call this method without creating a separate array or list:

C#
int total = CalculateTotal([10, 20, 30, 40]);

The compiler uses the method parameter type to determine the target collection type.

This makes method calls shorter and avoids introducing temporary variables when the collection is only needed once.

Another example is passing supported file extensions to a validation method:

C#
public static bool IsSupportedFile(string extension)
{
    string[] allowedExtensions =
    [
        ".pdf",
        ".docx",
        ".xlsx"
    ];

    return allowedExtensions.Contains(extension);
}

Collection expressions work particularly well for small, predefined collections passed directly to methods.

Working With Nested Collections

Collection expressions also support nested initialization.

This is useful when working with multidimensional data structures, configuration groups, or predefined test data.

Consider a jagged array:

C#
int[][] matrix =
[
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

Each inner collection expression creates an array of integers.

You can access the values using the normal array syntax:

C#
Console.WriteLine(matrix[0][1]);

// Output: 2

This syntax is easier to read than creating multiple arrays separately and assigning them to a parent array.

It is particularly helpful when preparing sample data for unit tests or working with grouped application settings.

Collection Expressions and Traditional Initialization

Collection expressions do not replace every existing collection initialization approach. Developers should understand where each option is useful.

Feature

Traditional initialization

Collection expressions

Array

new int[] { 1, 2, 3 }

[1, 2, 3]

List

new List<int> { 1, 2, 3 }

List<int> values = [1, 2, 3]

Empty array

Array.Empty<int>()

int[] values = []

Combining collections

AddRange()

[ .. first, .. second ]

Span

new Span<int>(array)

Span<int> values = [1, 2, 3]

Nested arrays

Multiple initializers

[[1, 2], [3, 4]]

The main advantage is consistent syntax. However, the traditional approach is still useful when you need explicit constructors, specific initialization behavior, or operations that collection expressions do not support.

Advantages and Disadvantages of Collection Expressions

Advantages

  1. Less initialization code: Developers can create arrays and lists without repeatedly writing constructor and initializer syntax.

  2. Consistent syntax: Different supported collection types can use the same square-bracket notation.

  3. Easier collection merging: Spread elements make it convenient to combine multiple collections.

  4. Better readability: Small collections and predefined values become easier to understand.

  5. Compiler optimization opportunities: The compiler can select suitable allocation strategies based on the target type and usage.

Disadvantages

  1. Target typing requirements: Collection expressions cannot always determine their collection type independently.

  2. Overload ambiguity: Methods accepting multiple collection types may require an explicit target type or cast.

  3. Eager collection creation: Collection expressions create a collection containing their elements rather than a lazy sequence.

  4. Limited initialization scenarios: They cannot replace every constructor or factory method.

  5. Learning curve: Developers need to understand spread elements, target typing, and supported collection conversions.

Best Practices for Using Collection Expressions

Collection expressions make initialization easier, but using them appropriately is important for maintainable application code.

Use Explicit Types When Necessary

Avoid using collection expressions with var when the compiler cannot infer the intended type.

Instead of:

C#
var roles = ["Admin", "User"];

Use:

C#
string[] roles = ["Admin", "User"];

This makes the collection type clear to both the compiler and other developers.

Use Spread Elements for Readable Collection Composition

When combining existing collections, spread elements can make the intention clear.

C#
int[] defaultPermissions = [1, 2, 3];

int[] additionalPermissions = [4, 5];

int[] allPermissions =
    [.. defaultPermissions, .. additionalPermissions];

However, do not use spread elements simply to make every collection operation shorter. If you need filtering, grouping, or transformation, LINQ may be a better choice.

Understand Memory Allocation

Collection expressions provide the compiler with opportunities to optimize collection creation.

For example, a collection expression targeting a Span or ReadOnlySpan may use stack allocation where appropriate.

However, this does not mean every collection expression is allocation-free.

Arrays and lists generally require collection storage, and spreading existing collections involves enumerating their elements.

For performance-sensitive code, understand the target collection and measure the actual behavior rather than assuming the shorter syntax is automatically faster.

Use Collection Expressions for Small Predefined Collections

They are particularly useful for configuration values, test data, supported file types, and method arguments.

For complex collection construction involving custom logic, explicit constructors or collection builders may provide better clarity.

Common Mistakes and Troubleshooting

Problem

Possible reason

Recommended solution

Collection expression does not compile

Target type is missing

Declare an explicit collection type

Spread element produces an error

The source cannot be enumerated

Use an enumerable collection

Method call is ambiguous

Multiple overloads accept different collection types

Provide an explicit target type or cast

Unexpected memory allocation

Collection expression creates an actual collection

Review the target type and allocation requirements

Collection cannot be initialized

The target type does not support collection expression conversion

Use a supported collection type or a collection builder

Collection behaves differently than expected

Target type determines the resulting collection implementation

Check the target type and its behavior

One important detail is that collection expressions cannot be used as compile-time constants or as default values for optional method parameters. They also do not provide lazy evaluation.

Understanding these restrictions helps avoid unnecessary compilation errors and unexpected behavior.

Summary

Collection expressions make everyday C# development simpler by providing a consistent way to initialize arrays, lists, spans, and other supported collection types.

Introduced in C# 12, this feature reduces repetitive initialization syntax and makes collection composition easier through spread elements.

For developers, the biggest benefit is readability. Instead of writing different initialization patterns for different collection types, you can use square brackets and let the compiler determine the appropriate implementation from the target type.

However, collection expressions should be used with an understanding of target typing, memory allocation, and collection behavior. They are not a replacement for LINQ, constructors, or every traditional initialization technique.

When used appropriately, collection expressions help reduce unnecessary code and make everyday C# applications easier to read, maintain, and develop.