0

I am developing a C# application. I have this kind of generic method with a type parameter:

public abstract class StuffDoer
{
  public abstract void DoStuff();
}
public class MyStuffDoer : StuffDoer
{
  public override void DoStuff()
  {
    /* We do stuff here */
  }
}

/* ... */

public void CreateAndDoStuff<T>() where T: StuffDoer, new()
{
  T instance = new T();
  instance.DoStuff();
}

public void MyCreateAndDoStuff()
{
  CreateAndDoStuff<MyStuffDoer>();
}

However, I'd like to pass the type parameter in the actual method parameters so the type could be decided dynamically. In other words, I'd like to do something like this (example is not valid C# but should illustrate the point):

public void CreateAndDoStuff(Type t) where t: StuffDoer, new()
{
  t instance = new t();
  instance.DoStuff();
}
public void MyCreateAndDoStuff()
{
  CreateAndDoStuff(typeof(MyStuffDoer));
}

Is this kind of thing somehow possible in C#?

user53739
  • 37
  • 7
  • You need to use reflection, like here: https://stackoverflow.com/questions/3255697/using-c-sharp-reflection-to-call-a-constructor – Russ Jan 06 '21 at 15:51
  • Does this answer your question? [How to create a new object instance from a Type](https://stackoverflow.com/questions/752/how-to-create-a-new-object-instance-from-a-type) and [Create instance of generic class with dynamic generic type parameter](https://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection) and [Create instance of generic class with dynamic generic type parameter](https://stackoverflow.com/questions/43899490/create-instance-of-generic-class-with-dynamic-generic-type-parameter) –  Jan 06 '21 at 16:00

0 Answers0