📚 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.
