Fake
Fake

Reputation: 131

c# inheritance - how to check type of child

I have an abstract class named Card, and two classes which inherit from this named Minion and Spell. I have also a list of Card(s) where i save either minion or spell. Finally i have a method to work with each Card in this list and it returs values based on type of card (minion or spell). So it looks like:

abstract class Card
{
    string name;
}

class Minion : Card
{
    public int attack;
}

class Spell : Card
{
    public int cost;
}

class Game
{
    List<Card> cards;

    private void ReadCards()
    {
        cards = new List<Card>();
        //READ CARDS FROM DATABASE AND ADD TO COLLECTION
        //cards.Add(new Minion()) or cards.Add(new Spell())
    }

    private int GetInfo(Card card)
    {
        //IF card IS A MINION return card.attack; OTHERWISE return card.cost;
    }
}

The issue is I'm not sure how "GetInfo" should look like to work properly. I've tried something like this:

private int GetInfo(Card card)
{
    if(card.GetType() == typeof(Minion))
    {
        return (Minion)card.attack;
    } else return (Spell)card.cost;
}

But it says attack and cost doesn't belong to Card. It's important for me to keep cards in one list instead of dividing them into two.

Upvotes: 0

Views: 198

Answers (2)

d219
d219

Reputation: 2845

To just do what you have asked for then you can make GetInfo an abstract method of Card and write in the functionality for each of your classes that inherit Card, something like the below:

    abstract class Card
    {
        string name;

        abstract protected int GetInfo();
    }

    class Minion : Card
    {
        public int attack;

        protected override int GetInfo()
        {
            return this.attack;
        }
    }

    class Spell : Card
    {
        public int cost;

        protected override int GetInfo()
        {
            return this.cost;
        }
    }

    class Game
    {
        List<Card> cards;

        private void ReadCards()
        {
            cards = new List<Card>();
            //READ CARDS FROM DATABASE AND ADD TO COLLECTION
            //cards.Add(new Minion()) or cards.Add(new Spell())
        }
    }

Upvotes: 1

Peter Karman
Peter Karman

Reputation: 111

That's because those properties are not part of the base class Card. If class B and C both derive from A, and your method accepts a parameter of type A, you can only use the members of type A not B and C. To accomplish what you want, you could have a method on the base class called GetInfo(). Then you can override that method in each class for their specified behavior. Of course there are many other(better?) Ways to do it but that would be most similar to what you're trying to do.

Upvotes: 0

Related Questions