Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C# Collection Expressions: Write Cleaner Code with `[]` Syntax

- 29.08.26 - ErcanOPAK

🎯 Key Insights: Collection expressions bring a unified, clean syntax for creating arrays, spans, lists, and more. Say goodbye to `new int[]` and `new List<T>` boilerplate!

Writing collection initialization in C# has always been verbose. Collection expressions (C# 12+) change everything.

❌ The Old Way – Verbose and Inconsistent

// ❌ Different syntax for different types
var array = new int[] { 1, 2, 3, 4, 5 };
var list = new List<int> { 1, 2, 3, 4, 5 };
var span = new Span<int>(new int[] { 1, 2, 3, 4, 5 });
var hashSet = new HashSet<int> { 1, 2, 3, 4, 5 };

// ❌ Empty collections
var emptyArray = Array.Empty<int>();
var emptyList = new List<int>();

✅ The New Way – Unified and Clean

// ✅ Same syntax for ALL collection types!
int[] array = [1, 2, 3, 4, 5];
List<int> list = [1, 2, 3, 4, 5];
Span<int> span = [1, 2, 3, 4, 5];
HashSet<int> hashSet = [1, 2, 3, 4, 5];
IEnumerable<int> enumerable = [1, 2, 3, 4, 5];

// ✅ Empty collections
int[] emptyArray = [];
List<string> emptyList = [];
HashSet<bool> emptySet = [];

// ✅ Type inference where possible
var numbers = new int[] { 1, 2, 3 }; // Still needs 'new int[]'
int[] numbers = [1, 2, 3];           // Type explicit

🚀 The Spread Operator – Combine Collections

// ✅ Spread operator (..) - Combine effortlessly
int[] first = [1, 2, 3];
int[] second = [4, 5, 6];
int[] combined = [..first, ..second, 7, 8, 9];
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

// ✅ With strings
string[] names = ["Alice", "Bob"];
string[] moreNames = [..names, "Charlie", "David"];
// Result: ["Alice", "Bob", "Charlie", "David"]

// ✅ With complex objects
var users = new[]
{
    new User("Alice", 25),
    new User("Bob", 30)
};

var moreUsers = [..users, new User("Charlie", 35)];

💡 Real-World: API Response Builder

// ✅ Clean API response construction
public class ApiResponseBuilder
{
    public static ApiResponse<T> Success<T>(T data, string message = "Success")
    {
        return new ApiResponse<T>
        {
            Status = "Success",
            Message = message,
            Data = data,
            // ✅ Collection expressions
            Errors = [],
            Metadata = new Dictionary<string, object>
            [
                ["Timestamp", DateTime.UtcNow],
                ["Version", "1.0.0"]
            ]
        };
    }
    
    public static ApiResponse<T> Error<T>(string message, params string[] errors)
    {
        return new ApiResponse<T>
        {
            Status = "Error",
            Message = message,
            Data = default,
            // ✅ Collection expressions with spread
            Errors = [..errors],
            Metadata = []
        };
    }
}

// ✅ Usage
var response = ApiResponseBuilder.Success(
    new Product { Id = 1, Name = "Laptop" },
    "Product retrieved successfully"
);

var errorResponse = ApiResponseBuilder.Error<Product>(
    "Validation failed",
    "Name is required",
    "Price must be positive"
);

📊 Collection Expressions: Before vs After

Operation Before After Char Reduction
Array Creation new int[] { 1, 2, 3 } [1, 2, 3] 60%
List Creation new List<int> { 1, 2, 3 } [1, 2, 3] 65%
Empty Array Array.Empty<int>() [] 80%
Combine Arrays first.Concat(second).ToArray() [..first, ..second] 70%

💡 Pro Tip: Collection Expressions Performance

// ✅ Compiler optimizes collection expressions
// Behind the scenes:
// - For arrays: uses stackalloc when possible
// - For lists: uses CollectionBuilder attribute
// - For spans: directly creates span

// ✅ Performance benchmark
int[] numbers = [1, 2, 3, 4, 5]; // Optimized
Span<int> span = [1, 2, 3, 4, 5]; // Stack allocation!

// ⚠️ Note: Collection expressions are compile-time features
// No runtime performance penalty!

📝 Summary Checklist

✅ Use [..] for all collection types
✅ Use spread (..) for combining collections
✅ Use [] for empty collections
✅ Use in method parameters for cleaner calls
✅ Use with Dictionary initialization
❌ Don't use with dynamic types
❌ Don't use when collection type cannot be inferred

Related posts:

ASP.NET Core “ValidateOnStart” — Stop Production Crashes at Runtime

ASP.NET Core “ValidateOnStart” — Stop Production Crashes at Runtime

C#: Why a Try/Finally Block Doesn't Run When the Process Is Killed

C#: Why a Try/Finally Block Doesn't Run When the Process Is Killed

Why LINQ in Hot Paths Can Kill Performance

Why LINQ in Hot Paths Can Kill Performance

Views: 14

Post navigation

JavaScript Debounce and Throttle: Control Event Frequency Like a Pro
ASP.NET Core API Versioning: Manage Multiple Versions Like a Pro

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (482)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com