How to use a class's type as the type argument for an inherited collection property in C#

Posted by Edelweiss Peimann on Stack Overflow See other posts from Stack Overflow or by Edelweiss Peimann
Published on 2012-09-23T21:34:22Z Indexed on 2012/09/23 21:37 UTC
Read the original article Hit count: 230

Filed under:
|
|
|
|

I am trying to create a representation of various types of card that inherit from a generic card class and which all contain references to their owning decks.

I tried re-declaring them, as suggested here, but it still won't convert to the specific card type.

The code I currently have is as such:

public class Deck<T> : List<T> 
    where T : Card 
{
    void Shuffle()
    {
        throw new NotImplementedException("Shuffle not yet implemented.");
    }
}

public class Card
{
    public Deck<Card> OwningDeck { get; set; }
}

public class FooCard : Card
{
    public Deck<FooCard> OwningDeck
    {
        get
        {
            return (Deck<FooCard>)base.OwningDeck;
        }
        set
        {
            OwningDeck = value;
        }
    }
}

The compile-time error I am getting: Error 2 Cannot convert type 'Game.Cards.Deck' to 'Game.Cards.Deck'

And a warning suggesting I use a new operator to specify that the hiding is intentional. Would doing so be a violation of convention? Is there a better way?

My question to stackoverflow is this: Can what I am trying to do be done elegantly in the .NET type system? If so, can some examples be provided?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET