Jack
Jack

Reputation: 15872

How can I create a generic collection which contains a specific type?

In C# I would like to create a generic deck of cards. Enabling me to e.g. Create a stack of cards, a queue of cards or any other collection of cards? Providing that this collection is a derived from IEnumerable.

public class Deck<T> where T : IEnumerable
{
    private T<ICard> __Cards;

    public Deck() : this(52){}

    public Deck(int cards)
    {
        __Cards = new T<Card>(cards);
    }
}

Some other class... calling

Deck<List> _Deck = new Deck<List>();

I get the following error:

The type parameter 'T' cannot be used with type arguments

Upvotes: 3

Views: 158

Answers (1)

JaredPar
JaredPar

Reputation: 754725

I think this is a case that would be better solved with inheritance

public abstract class Deck 
{
  public abstract ICard this[int index]
  {
    get;
    set;
  }

  protected void Create(int cardCount);
}

public sealed class DeckList : Deck
{
  private List<ICard> m_list;
  public override ICard this[int index] 
  {
    get { return m_list[index]; }
    set { m_list[index] = value; }
  }
  protected override void Create(int cards) 
  {
    m_list = new List<ICard>(cards);
  }
}

If you continue down the generic path I think you will ultimately find that you need a type with 2 generic parameters

  • The collection type
  • The element type

Example

public class Deck<TElement, TCollection> 
  where TCollection : IEnumerable<TElement>

Upvotes: 3

Related Questions