user2229618
user2229618

Reputation: 125

Getting Child type in base class to pass as type parameter to another method

I have a base class called Powerup and 2 descendent classes Bomb and Repel.

I have a method that needs to get called where I pass the object type as a parameter.

public void PowerupExpired<T>() where T : Powerup {
    //do stuff here
}

Is there any way from the base class Powerup I can get the child class type and pass it to the method? I cannot use Generic types. The type I pass to the method has to be of type Powerup

Right now, I am getting around by in the Powerup class using:

if (this is BombPowerup)
   PowerupManager.PowerupExpired<BombPowerup>();
else if (this is RepelPowerup)
   PowerupManager.PowerupExpired<RepelPowerup>();
//etc etc

Though this isn't neat or extensible.

EDIT:

I forgot to add. The reason I cannot have Generic Types is because I am going on to use the Unity GetComponent<T>() method using the parameter type pass through in PowerupExpired, which does not accept generic types.

Upvotes: 1

Views: 4267

Answers (3)

T. Kiley
T. Kiley

Reputation: 2802

If your only reason for having the generic method is to use the generic unity method, don't use the generic unity method.

There is an alternative method GetComponent(Type t) where you pass in the type (it's actually more robust, you can, for example, pass in interfaces instead of classes that inherit from component).

Your code would looking (something like):

public void PowerupExpired(PowerUp p)
{
    PowerUp powerUpComponent = GetComponent(p.GetType());
}

where

class BombPowerup : Powerup
{}

and

class RepelPowerup : Powerup
{}

and presumably

class Powerup : Component
{}

Upvotes: 1

David Arno
David Arno

Reputation: 43264

From your code, it looks very much like you want to do different things in PowerupExpired Depending on whether it's a bomb or repel. So why not have two methods?

Upvotes: 1

Ondrej Janacek
Ondrej Janacek

Reputation: 12626

Do you mean something like the following? I don't really understand what do you want exactly, but I gave it a shot.

Make Powerup an abstract class, just a base class for all other powerups.

public abstract class Powerup
{
    // common behaviour for all powerups       
}

Then every kind of a powerup will inherit from this base class.

public class BombPowerup : Powerup
{
    // specific behaviour
}

Declare PowerupExpired method so that it takes a parameter.

public void PowerupExpired<T>(T param) where T : Powerup
{
    // for example print a type of an argument
    Console.WriteLine(param.GetType().Name);
}

Try out.

PowerupExpired(new BombPowerup());

Upvotes: 1

Related Questions