DEV Community

El Mehdi Taii
El Mehdi Taii

Posted on

πŸš€ Simplify Your C# Collections with the Spread Operator (..)

If you're still using Array.Copy(), .Concat(), or .AddRange() to combine collections in C#, you're working too hard. C# 13 introduced the spread operator (..) that makes collection manipulation cleaner, faster, and more intuitive.

The Problem

Traditional collection operations in C# are verbose and require multiple steps. Whether you're combining arrays, adding elements, or copying collections, you end up with code that's harder to read and maintain.

The Solution: Spread Operator (..)

The spread operator (..) lets you expand collections inline, making your code more expressive and eliminating boilerplate. Think of it as "unpacking" a collection right where you need it.
Code Examples

1️⃣** Basic Collection Combining**

2️⃣ Adding Elements to Collections

3️⃣ Working with Different Collection Types

4️⃣ Real-World Use Case: Building Configuration

5️⃣ Creating Copies

6️⃣ API Response Building

Key Benefits
βœ… Readability: Code intention is crystal clear
βœ… Less Boilerplate: No more manual array copying or .Concat() chains
βœ… Type Safe: Full compile-time type checking
βœ… Performance: Efficient memory allocation
βœ… Flexibility: Works with any IEnumerable

Performance Comparison

Best Practices
πŸ”Ή Use spread operator for:

Combining multiple collections
Creating collection copies
Building collections with mixed sources
Dynamic collection composition

πŸ”Ή Remember:

Creates shallow copies (like most collection operations)
Works with any IEnumerable type
Can be mixed with individual elements
Multiple spreads in one expression are fine

πŸ”Ή Common Patterns:

Requirements
⚠️ Note: The spread operator requires:

C# 13 or later
.NET 9 or later

If you're on older versions, stick with traditional methods like .Concat(), .AddRange(), or Array.Copy().
When NOT to Use Spread Operator
πŸ”Ή If you need to modify elements during combination (use LINQ .Select() instead)
πŸ”Ή If you're working with very large collections and need specific performance optimizations
πŸ”Ή If you're on C# 12 or earlier (not available)
The Bottom Line
The spread operator is a small syntax addition that makes a huge difference in code clarity. If you're building, combining, or copying collections, stop writing boilerplate and start using ... Your future self (and your code reviewers) will thank you.

Top comments (0)