Collection Initializer

If you want to use collection initializer to initialize a instance of a collection class, there are two prerequisites:

  • The collection class must implement IEnumerable.
  • The collection class must have corresponding Add() methods whose parameters are consistent with the items in the collection. The Add() method could be a static extension method out side the collection class.
public class Card
{
	public Card(Suit suit, Ranking ranking)
	{
		Suit = suit;
		Ranking = ranking;
	}
	
	// ...
}

public class Deck : IEnumerable<Card>
{
	//...
	
	public void Add(Card card)
	{
		// Accept a Card instance
	}
}

public static class CardExension
{
	public static void Add(this Deck deck, Suit suit, Ranking ranking)
	{
		var card = GenerateCard(suit, ranking);
		deck.Add(card);
	}
}

class Program
{
	static void Main()
	{
		Deck deck = new Deck
		{
			new Card(Suit.Heart, Ranking.Queen),
			{Suit.Spade, Ranking.One },
		};
		foreach (var card in deck)
			Console.WriteLine(card);
	}
}

Leave a comment