Get a child from array of abstract classes

I have abstract class Ship and 2 other classes are inherited from it Battleship and Cruiser.

public abstract class Ship
{
    public Vector2Int Position;
    public int Size;

    public abstract void Move();
    public abstract void Attack();
}

public class Cruiser : Ship
{
    public override void Attack()
    {
        Debug.Log("ATTACK");
    }

    public override void Move()
    {
        Debug.Log("Moves forward at a speed of 2 cell per step");
    }
}

public class Battleship : Ship
{
    public override void Attack()
    {
        Debug.Log("ATTACK");
    }

    public override void Move()
    {
        Debug.Log("Moves forward at a speed of 1 cell per step");
    }
}

Is it possible to get a reference to a child class from an abstract one?

public class Main
{
    private Ship[] _ships = new Ship[] { new Battleship(), new Battleship(), new Cruiser() };

    public void StepUpdate()
    {
        for (int i = 0; i < _ships.Length; i++)
        {
            _ships[i].Move();
            _ships[i].Attack();

            //_ships[i] is Battleship or Cruiser !?
            //Battleship bs = _ships[i] ?
        }
    }

}

So you know, it’s known as a “derived” class, not a “child” class.

You can do:

var myShip = _ships[i];

if (myShip is BattleShip)
{
    BattleShip bs = myShip as BattleShip;
}
else if (myShip is Cruiser)
{
    Cruiser cr = myShip as Cruiser;
}

You can explicitly cast too:

BattleShip bs = (BattleShip)myShip;

You can also get the type and use a switch statement on the type.

Other ways to do it too. The main concern is how scalable this is as the number of types goes up along with the number of places you need to add such special code handling.

1 Like