Home > Software engineering >  How to use Type of inheriting class as parameter
How to use Type of inheriting class as parameter

Time:07-19

I have a base class (can also be an interface) and n-classes that extend the base class. I want to have a function that excepts only classes of the base class type.

Currently I am doing something like this

abstract class BaseClass{
  public abstract void Execute();
}

class MyClass : BaseClass {
  public void Execute(){
    //my code
  }
}

[...]

MyFunction(Type param)
{
  //check if param is type of BaseClass. If not, throw exception 
}

The problem with this implementation is, that I can pass any type of class. My goal is to prevent this.

Like in TypeScript you can do this

myFunction(param: {new (): BaseClass}){
   //my code
}

Is there a similar approach I can use in C#?

CodePudding user response:

There's a couple of things you can do, depending on what you actually want to do in the function. Stating your actual use case makes it easier to come up with a solution.

Looking at the typescript code it looks like you want to be able to call the constructor inside the function to produce an instance of the given type that derives from BaseClass.

In this case I'd try using generics:

public void MyFunction<T>() where T: BaseClass, new()
{
  T myClass = new T();
  //Do stuff...
}

This works with interfaces/classes. It will only accept types deriving from BaseClass.

CodePudding user response:

Edit: updated my answer after being notified how my previous answer wouldn't know if it was a grandchild of the base class

public abstract class BaseClass
{
    public abstract void Test();
}

public class DerivedFromBase : BaseClass
{
    public override void Test(){}
}

public class Grandchild : DerivedFromBase 
{
}

public class Main
{
    Grandchild aClass= new Grandchild(); // Instantiate Normally

    UseIfOnlyTypeOfBaseClass(aClass);// Use Method with check like this
}

private void UseIfOnlyTypeOfBaseClass<T>(T param)
{
    if (typeof(T).IsSubclassOf(typeof(BaseClass)))
    {
        Console.WriteLine("Match");
    }
}
  • Related