Java ใช้ Double Brace Initialization สร้างและ Initialize Collection ใน Expression เดียว ใน C# ใช้ Collection Initializer ซึ่งสะดวกกว่าและเป็น Idiomatic C#
Java Double Brace Initialization
// Java - Anonymous Inner Class + Instance Initializer
List list = new ArrayList() {{
add("One");
add("Two");
add("Three");
add("Four");
}};
C# Collection Initializer (Standard)
// C# - Clean, Readable, No Extra Class
var list = new List { "One", "Two", "Three", "Four" };
C# Collection Initializer แบบสมบูรณ์
// List
var numbers = new List { 1, 2, 3, 4, 5 };
// Dictionary
var dict = new Dictionary
{
["apple"] = 1,
["banana"] = 2,
["cherry"] = 3
};
// HashSet
var set = new HashSet { "red", "green", "blue" };
// Custom Class with Add Method
public class MyCollection : IEnumerable
{
private List _items = new List();
public void Add(int item) => _items.Add(item);
public IEnumerator GetEnumerator() => _items.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
var custom = new MyCollection { 10, 20, 30 };
Object Initializer (สำหรับ Properties)
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}
var person = new Person
{
Name = "John",
Age = 30,
Address = new Address { City = "Bangkok", Country = "Thailand" }
};
Index Initializer (C# 6+ Dictionary)
var dict = new Dictionary
{
[0] = "Zero",
[1] = "One",
[2] = "Two"
};
เพิ่ม Add Method ให้ Class เอง (รองรับ Collection Initializer)
public class MyQueue
{
private Queue _queue = new Queue();
public void Add(T item) => _queue.Enqueue(item); // ต้องมี Add Method
public IEnumerator GetEnumerator() => _queue.GetEnumerator();
}
// ใช้ได้
var queue = new MyQueue { 1, 2, 3 };
เปรียบเทียบ
| ด้าน | Java Double Brace | C# Collection Initializer |
|---|---|---|
| Syntax | {{ ... }} | { ... } |
| Creates Extra Class | ใช่ (Anonymous Inner Class) | ไม่ |
| Memory Overhead | มี (Class Instance) | ไม่มี |
| Serialization | ซับซ้อน | ง่าย (Standard Object) |
| Readability | ต่ำ | สูง |
สรุป
C# Collection Initializer ดีกว่าในทุกมิติ: Syntax สะอาดกว่า ไม่สร้าง Class เฉพาะ ประสิทธิภาพดีกว่า และเป็น Standard Pattern ของ .NET