0

So I've got the following delegate:

delegate Task<T> Atsk<T>();

I have with it a series of overloaded constructors for a class. Based on the constructor used, the actual function I need to execute changes. While the types needed are known ahead of time, I won't know what they are until the appropriate arguments are passed to the constructor.

If these are the constructors:

myClass (int a) myClass (int a, int b) myClass (int a, string b)

Based on this, I'd like to do the following:

Atsk<Type1> atsk = new Atsk<Type1>(myFunc); if object created with the first constructor

Atsk<Type2> atsk = new Atsk<Type2>(myFunc); if object created with the second constructor

Atsk<Type3> atsk = new Atsk<Type3>(myFunc); if object created with the third constructor

Now, by using conditional logic and hardcoding the type and function, it works, but I am thinking it would be nice if I could set the type and function required in the constructor as well so that the only line of code I'd need is:

Atsk<myVariableType> atsk = new Atsk<myVariableType>(myVariableFunc);

intuitively, this feels like it should be possible using some kind of lambda that defines the proper things I need in the various constructors, though I can't figure it out. The Type class also didn't seem to work.

user3657661
  • 306
  • 3
  • 13
  • 1
    Generics are compile-time unfortunately, meaning they cannot be created using a `Type` object. You may need to use reflection to achieve creating of dynamic generics [(1)](https://stackoverflow.com/a/4101821/1481699) [(2)](https://stackoverflow.com/a/232621/) – Prime Feb 07 '19 at 22:43
  • See: [`Type.MakeGenericType(Type[])`](https://learn.microsoft.com/en-us/dotnet/api/system.type.makegenerictype) – Prime Feb 07 '19 at 22:49

0 Answers0