3

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
Jack
  • 15,614
  • 19
  • 67
  • 92
  • 4
    Suppose your code worked. What would be the gain in writing `Deck` instead of just `List`? – Jon Feb 24 '14 at 21:01
  • relevant for this as addition to Jon's remark: http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt – Vogel612 Feb 24 '14 at 21:02

1 Answers1

3

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>
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454