---
# System prepended metadata

title: Collection initializers (集合初始化器)
tags: [' initializers', ' collection', ' list', c#]

---

---
tags: c#, collection, list, initializers
---

# Collection initializers (集合初始化器)

這是一個在 c# 3引入的語法，使用於 List初始化時立即加入物件。
Example : 
```csharp=
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };  

List<Cat> moreCats = new List<Cat>
{
    new Cat{ Name = "Furrytail", Age=5 },
    new Cat{ Name = "Peaches", Age=4 },
    null
};
```

如果需要再 POCO( A Plain Old CLR/C# Object is a POCO)中加入 collection initialuzers，則必須在物件中加入一個 Add()方法。
Example : 
```csharp=
public class PokerHands : IEnumerable<Card>
{
    private IEnumerable<Card> _cards;

    public PokerHands(IEnumerable<Card> cards)
    {
        _cards = cards;
    }

    public PokerHands()
    {
        _cards = new List<Card>();
    }

    public IEnumerator<Card> GetEnumerator()
    {
        return _cards.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Add(Card card)
    {
        var newCards = _cards.ToList();
        newCards.Add(card);
        _cards = newCards;
    }
}

var pokerHands = new PokerHands
{
    new()
    {
        Value = "2C"
    },
    new()
    {
        Value = "3H"
    },
    new()
    {
        Value = "4S"
    },
    new()
    {
        Value = "8C"
    },
    new()
    {
        Value = "AH"
    }
};

```

如果今天要在一個沒有權限修改的物件加入初始化器，可以使用擴充方法去騙過 Compile。
Example : 
```csharp=
public class PokerHands : IEnumerable<Card>
{
    private IEnumerable<Card> _cards;

    public PokerHands(IEnumerable<Card> cards)
    {
        _cards = cards;
    }

    public PokerHands()
    {
        _cards = new List<Card>();
    }

    public IEnumerator<Card> GetEnumerator()
    {
        return _cards.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Insert(Card card)
    {
        var newCards = _cards.ToList();
        newCards.Add(card);
        _cards = newCards;
    }
}

public static class PokerHandsExtensions
{
    public static PokerHands Add(this PokerHands pokerHands, Card card)
    {
        pokerHands.Insert(card);

        return pokerHands;
    }
}

var pokerHands = new PokerHands
{
    new()
    {
        Value = "2C"
    },
    new()
    {
        Value = "3H"
    },
    new()
    {
        Value = "4S"
    },
    new()
    {
        Value = "8C"
    },
    new()
    {
        Value = "AH"
    }
};
```

除了 List之外，Dictionary也可以用類似的方法去實現初始化器功能，可參考 MSDN。


## Reference
[Object and Collection Initializers (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers)