C# collection expressions make it easier to create arrays, lists, spans, and other collection types. Instead of writing separate initialization syntax for different collection types, developers can use square brackets to define collection elements.
For example, an array and a list can now be initialized using almost identical syntax:
int[] numbers = [10, 20, 30];
List<int> values = [10, 20, 30];
This improves readability and reduces repetitive code. However, shorter syntax does not automatically mean better memory performance.
Collection expressions are target-typed, which means the compiler uses the expected destination type to determine how the collection should be created. Depending on that target type, the compiler may allocate an array, create a collection object, use temporary storage, or apply an optimization.
These differences become important in applications that create collections frequently, especially inside request handlers, background workers, data-processing pipelines, and performance-sensitive methods.
Understanding how collection expressions work helps developers use the feature without introducing unexpected memory allocations.
Understanding C# Collection Expressions
Collection expressions were introduced in C# 12. They use square brackets to define a collection of elements.
A traditional array initialization looks like this:
int[] numbers = new int[] { 10, 20, 30 };
The same code can be written using a collection expression:
int[] numbers = [10, 20, 30];
For a List, the traditional syntax is:
List<string> names = new List<string>
{
"John",
"David",
"Sarah"
};
With collection expressions, it becomes:
List<string> names = ["John", "David", "Sarah"];
The important difference is that a collection expression does not have a natural type of its own. Its destination determines the collection type.
For example:
int[] numbers = [1, 2, 3];
List<int> values = [1, 2, 3];
ReadOnlySpan<int> span = [1, 2, 3];
All three expressions use the same syntax, but they create values with different target types and different memory behavior.
You also cannot assign a collection expression directly to a variable declared with var:
// This does not compile
var numbers = [1, 2, 3];
The compiler cannot determine the intended collection type because no target type is available.
Instead, provide an explicit type:
var numbers = new[] { 1, 2, 3 };
Or use the collection expression with a declared destination type:
int[] numbers = [1, 2, 3];
Why Collection Expressions Can Allocate Memory
The collection expression syntax hides some of the work required to create a collection. The compiler determines how to construct the destination based on its target type and the elements being provided.
Consider the following examples:
int[] numbers = [1, 2, 3];
List<int> values = [1, 2, 3];
IEnumerable<int> items = [1, 2, 3];
Although the syntax is identical, these declarations do not have identical memory characteristics.
An array requires storage for its elements. A List requires a collection object and its internal storage. An interface target such as IEnumerable<int> still requires an actual collection to hold the values.
An important point is that a collection expression does not create a deferred sequence. When it is converted to IEnumerable<T>, the elements are materialized into an in-memory collection.
This is different from returning a LINQ query that may not execute until enumeration begins.
For example:
IEnumerable<int> GetNumbers()
{
return [1, 2, 3];
}
The collection is created when the method executes. The caller does not receive a query that generates the values only when requested.
This matters when developers use collection expressions as return values in frequently called methods.
Choosing the Right Target Type
The target type is one of the most important factors affecting allocation behavior.
The following table describes common choices:
Target type | Typical behavior | Important consideration |
|---|
int[] | Creates an array | Useful when an array is required |
List<int> | Creates a List and stores elements | Suitable for a mutable collection |
IEnumerable<int> | Materializes a collection | Does not provide deferred execution |
ReadOnlySpan<int> | Creates a span over contiguous storage | Storage lifetime and compiler optimizations matter |
Span<int> | Creates a writable span over contiguous storage | Useful for temporary or mutable data |
The compiler can optimize collection creation when it has enough information. For example, an empty collection expression may use Array.Empty<T>() when the target does not need to be modified.
However, developers should not assume that every collection expression avoids allocation or uses the same internal implementation.
The correct approach is to select the collection type based on how the data will be consumed.
If a method only needs to read a small sequence of values, a ReadOnlySpan<T> may be appropriate. If the caller needs to add or remove elements, a List<T> may be a better choice.
Using Span and ReadOnlySpan to Reduce Unnecessary Allocations
Span<T> and ReadOnlySpan<T> provide access to contiguous memory without requiring the caller to work directly with an array or List.
Collection expressions support both types:
ReadOnlySpan<int> statusCodes = [200, 201, 400, 404, 500];
foreach (int statusCode in statusCodes)
{
Console.WriteLine(statusCode);
}
This can be useful for small, fixed collections that are only read.
A writable span can also be initialized:
Span<int> values = [10, 20, 30];
values[0] = 100;
Console.WriteLine(values[0]);
The important advantage is that a span is a lightweight view over memory rather than a normal heap-allocated collection object.
However, this does not mean every collection expression targeting Span<T> or ReadOnlySpan<T> is guaranteed to use stack memory.
The compiler determines the appropriate storage based on the expression, lifetime requirements, and available optimizations. Depending on the situation, storage may be stack allocated or use another valid representation.
Spans also have lifetime restrictions. They are ref-like types and cannot be stored in ordinary class fields or used in every context where an array can be used.
Use spans when their lifetime and usage fit the application design. Do not replace every array or List with a span simply because it may reduce allocations.
Understanding the Spread Operator and Its Cost
Collection expressions support the spread operator, represented by two dots (..).
It allows developers to include elements from an existing collection in a new collection expression.
For example:
int[] first = [1, 2, 3];
int[] second = [4, 5, 6];
int[] combined = [.. first, .. second];
The resulting array contains:
1, 2, 3, 4, 5, 6
The syntax is convenient, but it is important to understand what happens to memory.
The expression creates a new destination collection containing the elements from both source collections. It does not simply connect the original arrays together.
If the source collections already contain many elements, the destination needs storage for all those elements.
For example:
List<int> first = Enumerable.Range(1, 1000).ToList();
List<int> second = Enumerable.Range(1001, 1000).ToList();
List<int> combined = [.. first, .. second];
The new List contains 2,000 elements. The original collections remain separate objects.
This can become expensive when the operation runs repeatedly inside a loop.
A method that combines several large collections for every incoming request may create unnecessary temporary objects and increase garbage collection activity.
When combining collections, consider whether a new collection is actually required. If the destination can be reused, adding elements to an existing collection may be more appropriate.
Avoiding Repeated Collection Creation in Hot Paths
One common performance mistake is creating a new collection every time a frequently executed method runs.
Consider this example:
public bool IsValidStatus(int status)
{
int[] allowedStatuses = [200, 201, 204];
return allowedStatuses.Contains(status);
}
The method creates a collection whenever it is called. If this method is executed thousands of times, repeated collection creation may contribute to unnecessary allocations.
For a small, fixed collection, a static readonly array can be a better choice:
private static readonly int[] AllowedStatuses =
[200, 201, 204];
public bool IsValidStatus(int status)
{
return AllowedStatuses.Contains(status);
}
Now the collection is created once when the type is initialized rather than every time the method executes.
If the values are only used for read-only checks, the implementation can also use a suitable read-only abstraction.
Another option is a switch expression:
public bool IsValidStatus(int status)
{
return status is 200 or 201 or 204;
}
For a small fixed set of values, this avoids creating a collection altogether.
The best solution depends on the operation. A collection is useful when the values need to be managed as data, but it is unnecessary when a simple condition expresses the requirement more clearly.
Measuring Allocation Costs Instead of Guessing
Collection expressions are compiler features, and their generated implementation can change based on the target type and compiler optimizations.
For that reason, developers should measure performance rather than assume that one syntax is always faster.
For a quick diagnostic, .NET provides GC.GetAllocatedBytesForCurrentThread():
long before = GC.GetAllocatedBytesForCurrentThread();
int[] values = [10, 20, 30, 40, 50];
long after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"Allocated bytes: {after - before}");
This can help identify allocations during a controlled section of code.
However, this simple measurement is not a complete benchmark. JIT compilation, runtime activity, and other allocations on the current thread can affect the result.
For more reliable comparisons, use BenchmarkDotNet and compare equivalent operations.
For example, compare array initialization, List initialization, and span-based processing using the same input values and workload.
Measure both execution time and allocated memory. Also test realistic collection sizes and repeated execution, because a difference that is insignificant for three elements may become important when processing thousands of elements.
Common Mistakes to Avoid
Mistake | Why it matters | Better approach |
|---|
Assuming collection expressions always avoid allocations | The destination collection may require heap storage | Check the target type |
Using IEnumerable<T> expecting deferred execution | Collection expressions materialize their elements | Use an iterator or LINQ query when deferred execution is required |
Creating collections inside frequently called methods | Repeated calls can create unnecessary objects | Reuse fixed data where appropriate |
Spreading large collections without considering copying | A new destination collection must hold the combined elements | Reuse a destination when possible |
Replacing arrays with spans everywhere | Spans have lifetime and usage restrictions | Choose based on the API and data lifetime |
Assuming stack allocation is guaranteed | Storage selection depends on compiler and lifetime rules | Measure and inspect the actual scenario |
Best Practices for Production Applications
When using collection expressions in production code, follow a few practical guidelines.
Choose the destination type based on how the collection will be used. Do not select a type only because its initialization syntax looks shorter.
Avoid creating fixed collections repeatedly inside hot methods. Store reusable values in static fields when appropriate.
Use ReadOnlySpan<T> for suitable read-only operations where its lifetime restrictions can be respected.
Review spread expressions when combining large collections. They create a new result rather than reusing the original storage.
Do not use IEnumerable<T> when you specifically need deferred execution. Use an iterator method or another lazy sequence implementation.
Benchmark performance-sensitive code using realistic data and workloads.
Keep code readable. A more complicated implementation is not automatically better simply because it may reduce a small allocation.
Summary
C# collection expressions provide a clean and consistent way to initialize arrays, lists, spans, and other supported collection types. They reduce repetitive syntax and make collection initialization easier to read.
However, collection expressions do not guarantee fewer memory allocations. Their behavior depends on the target type, the elements being supplied, and the optimizations performed by the compiler.
Developers should pay particular attention to interface targets, spread expressions, repeated collection creation, and the lifetime requirements of Span<T> and ReadOnlySpan<T>.
For production applications, the best approach is to choose the correct collection type, avoid unnecessary object creation in frequently executed code, and measure allocation costs when performance matters.
Collection expressions are a useful language feature, but good memory management still depends on understanding what the application actually creates.
Join the conversation! Your thoughts help the community grow.