Different objects from one interface with different methods and properties

Here is my interface

interface IEnemy
    {
        int Health { get; set; }
    }

and few classes that derive from it

public class Goblin : IEnemy
    {
        public int Health { get; set; }
        public Goblin()
        {
            Health = 50;
            Console.WriteLine("You encounter an Enemy Goblin!");
        }
    }
public class Undead : IEnemy
    {
        public int Health { get; set; }
        public Undead()
        {
            Health = 100;
            Console.WriteLine("You encounter an Enemy Undead!");
        }
    }
public class Orc : IEnemy
    {
        public int Health { get; set; }
        public Orc()
        {
            Health = 150;
            Console.WriteLine("You encounter an Enemy Orc!");
        }
    }

And let's say I want to make a randomizer which chooses which enemy to spawn---I make something like this

IEnemy enemy = new Goblin() or Undead() or Orc()...

And everything works as intended but for example when one object, let's say Goblin, has a method that the interface doesn't have, how can I call that method if the enemy is of type IEnemy?

Upvotes: 1

Views: 46

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112762

You can write

if (enemy is Goblin goblin) {
    goblin.CallGoblinMethod();
}

But the question is whether this is a good design. It would be preferable to have methods with an universal "taste", that are implemented differently in different objects. They might even be empty in some objects.

Or you could generalize a behavior through another interface

interface IThief
{
    void Steal();
}

public class Goblin : IEnemy, IThief
{
    public int Health { get; set; }
    public Goblin()
    {
        Health = 50;
        Console.WriteLine("You encounter an Enemy Goblin!");
    }

    public void Steal()
    {
        //TODO: steal
    }
}

Like this, you don't even need to know that the enemy is a Goblin. Other creatures could appear in the evolution of the game, that have the same ability.

if (enemy is IThief thief) {
    thief.Steal();
}

Upvotes: 2

Related Questions