Home > Enterprise >  Checking for instances through the base class
Checking for instances through the base class

Time:12-04

right now I am doing a game which requires Monsters. I made a MonsterBase class that every other monster will inherit from. This is a console game so I give every LowLevelMonster instance different coordinates. In a different method I want to check if the player is on the same coordinates as one of the monster instances. Right now i can only use an if statement to ask for the PositionX & PositionY of every monster instance. This scales terribly if I get to over 5 monsters.

My question: Since the other monster instances inherit from MonsterBase, is it possible to check for the PositionX & PositionY of MonsterBase that calls for every inhertied instance of it?

Something like:

if(Player.PositionX == MonsterBase.PositionX)
{
    Console.WriteLine("the names of the Monsters instances that have the same X Coordinates");
}

These are my current classes:

public class MonsterBase 
{
    int PositionX = 0;
    int PositionY = 0;
}

public class LowLevelMonster : MonsterBase
{
    string name = "monster";
    int HP = 5;
}

CodePudding user response:

Nope, this isn't how inheritance works, there's no implied link from an instance of the base class to an instance of the child.

You are going to have to keep a record of all your monsters in a collection, something like List<MonsterBase> or Collection<MonsterBase> then you can filter the list.

listOfMonsters.Where(monster => monster.PositionX == Player.PositionX)

What is a lambda expression

Think of a lambda expression as shorthand way to write a method.

Moving the expression monster => monster.PositionX == Player.PositionX to a variable will get you

Expression<Func<MonsterBase, bool>> lambda =
    monster => monster.PositionX == Player.PositionX;
listOfMonsters.Where(lambda);

This is a little easier to see what's happening. listOfMonsters.Where() expects a parameter of type Expression<Func<MonsterBase, bool>> where the lambda is essentially a method delegate that takes a single parameter (named monster) and returns a boolean value.

This could have also been written

public class Player() {
    public int PositionX { get; set; }

    public bool ComparePosition(MonsterBase monster){
        return monster.PositionX == Player.PositionX;
    }
}

// then later in the code
listOfMonsters.Where(Player.ComparePosition);

This is a different overload of Where that takes a method group which is essentially the same as.

listOfMonsters.Where(monster => Player.ComparePosition(monster));
  • Related