C# Spread Element .. — Complete Guide
In this tutorial, you'll learn about C# Spread Element ... We cover key concepts, practical examples, and best practices.
You have two arrays and need a combined third. You write a loop, call Concat, or use AddRange. These work but none are inline expressions you can use in a return statement. The spread element .. inside a collection expression merges collections inline.
Wrong
int[] first = [1, 2, 3];
int[] second = [4, 5, 6];
var combined = new List<int>(first.Length + second.Length);
combined.AddRange(first);
combined.AddRange(second);
// or
var combined = first.Concat(second).ToArray();
Output: Works. Multiple lines or multiple allocations.
Right
int[] first = [1, 2, 3];
int[] second = [4, 5, 6];
int[] combined = [..first, ..second, 7, 8];
Output: [1, 2, 3, 4, 5, 6, 7, 8] — single expression, single allocation (or zero allocation for Span<T>).
The spread element works with any collection type that supports collection expressions:
List<string> names = ["Alice", "Bob"];
List<string> more = ["Charlie"];
List<string> all = [..names, ..more, "Dave"];
// ["Alice", "Bob", "Charlie", "Dave"]
Prevention
- Use
..to merge collections in a single expression. - Use
..in return statements:return [.. GetBaseItems(), .. GetExtraItems()];. - Use
..to prepend or append items:[..existing, newItem]. - Use
..multiple times in one expression without performance concerns. - Use
..withSpan<T>for zero-allocation array concatenation. - Use
..in LINQ-like scenarios where you need combined sets.
Common Mistakes with spread element
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
The spread element is used in Doda Browser's extension manifest merging logic. For more C#, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro