user819640
user819640

Reputation: 250

Get class type of derived class in base class and pass it as a type parameter

I have a base class 'Powerup' and then 3 children of that class 'Bomb', 'Repel' and 'Wall'.

In the base class I want to get the derived class type so that I can pass it as a method parameter.

At the minute I get around this problem by using code like this:

if (this is BombPowerup)
   AddComponent<BombPowerup>();
else if (this is RepelPowerup)
   AddComponent<RepelPowerup>();
else if (this is WallPowerup)
   AddComponent<WallPowerup>();

But it is not really extensible. I understand I could create an abstract method and let the child classes do each line themselves, but I would like to know of a solution I could use in the base class for good learning.

Thanks.

EDIT: The method AddComponent is defined as follows

void AddComponent<T>() where T : Powerup

Upvotes: 1

Views: 749

Answers (1)

Lee
Lee

Reputation: 144136

You could do it using reflection:

var method = typeof(Powerup).GetMethod("AddComponent").MakeGenericMethod(this.GetType());
method.Invoke(this, new object[]);

alternatively you could add a generic type parameter to the base class and use that to call AddComponent:

public abstract class Powerup<T> where T : Powerup
{
    private void AddSelf()
    {
        this.AddComponent<T>();
    }
}

Upvotes: 2

Related Questions