Ricochet Ricochet - 1 month ago 14
C# Question

How to pass derived class as a parameter to a method that asks for a base class

Note I am a beginner.

I read through this this question and I understood that passing a derived class to a method that asks for a base class is totally ok and should work.

Well, I have a class "Enemy" that inherits "PhysicsObject".
However when I wrote the following collision handler and call it with a PhysicsObject and an Enemy:

void ProjectileHit(PhysicsObject p, PhysicsObject hit)
{
hit.TakeDamage(CurrentPlayer.EquippedTool.Damage);
}


I get a red line in visual studio saying
PhysicsObject does not contain a definition for "TakeDamage".
The collision handler is part of the framework I use and only accepts an instance of the base class it seems. Is there any way to pass an instance to "Enemy" to that handler and call "TakeDamage" inside of it?

EDIT:
Would this work?

void ProjectileHit(PhysicsObject p, PhysicsObject hit)
{
Enemy e = hit as Enemy;
e.TakeDamage(CurrentPlayer.EquippedTool.Damage);
}

Answer

As long as your PhysicsObject does not implement the method TakeDamage (and reading your class names it never should) you can do the following:

void ProjectileHit(PhysicsObject p, PhysicsObject hit)
{
    (hit as Enemy)?.TakeDamage(CurrentPlayer.EquippedTool.Damage);
}

'as' tries to cast hit to Enemy and returns null if hit is null or the cast fails.

'?' executes the code on its right only if the left side is not null.