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#: Use Collection Initializers for Clean Code

- 25.07.26 - ErcanOPAK

📚 Collection Initializers = Clean Code

Verbose collection creation is tedious. Collection initializers make code cleaner and more readable.

❌ Verbose Style

var list = new List<string>();
list.Add("Apple");
list.Add("Banana");
list.Add("Cherry");

var dict = new Dictionary<string, int>();
dict.Add("One", 1);
dict.Add("Two", 2);
dict.Add("Three", 3);

✅ Collection Initializer

var list = new List<string>
{
    "Apple", "Banana", "Cherry"
};

var dict = new Dictionary<string, int>
{
    ["One"] = 1,
    ["Two"] = 2,
    ["Three"] = 3
};

🎯 Advanced Examples

// Complex Objects
var users = new List<User>
{
    new User { Id = 1, Name = "Alice", Age = 25 },
    new User { Id = 2, Name = "Bob", Age = 30 },
    new User { Id = 3, Name = "Charlie", Age = 35 }
};

// Nested Collections
var matrix = new List<List<int>>
{
    new List<int> { 1, 2, 3 },
    new List<int> { 4, 5, 6 },
    new List<int> { 7, 8, 9 }
};

// Dictionary with Complex Values
var employeeData = new Dictionary<string, Employee>
{
    ["E001"] = new Employee { Name = "John", Department = "IT" },
    ["E002"] = new Employee { Name = "Jane", Department = "HR" }
};

// Arrays with Initializer
int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = { "Alice", "Bob", "Charlie" };

// Collection Initializers with LINQ
var filtered = new List<int>
{
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}.Where(x => x % 2 == 0).ToList();

// Custom Collection with Add method
public class CustomCollection : IEnumerable<int>
{
    public void Add(int item) { /* implementation */ }
    public IEnumerator<int> GetEnumerator() { /* implementation */ }
}

var custom = new CustomCollection { 1, 2, 3, 4, 5 };

💡 Collection Initializer Tips

  • Use for List, Dictionary, and arrays
  • Use indexers for Dictionary
  • Can create custom collections
  • Combine with object initializers
  • Improves code readability

Collection initializers make C# code more expressive and less cluttered. They’re a small feature with big impact.

— Clean Code Advocate

Related posts:

C#: Fix a Regex Marked RegexOptions.Compiled That Silently Makes Startup Slower Without Making Match...

C#: Fix a Regex Marked RegexOptions.Compiled That Silently Makes Startup Slower Without Making Match...

C#: Use Generics for Type-Safe Code

C#: Use Generics for Type-Safe Code

C#: Use Records for Immutable Data Types

C#: Use Records for Immutable Data Types

Views: 13

Post navigation

SQL: Optimize Performance with Stored Procedures
C#: Eliminate Null Reference Exceptions with Nullable Types

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,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (608)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

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

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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