-2

I have 4 interfaces that looks like this:

IBaseInter {}
IInterA : IBaseInter {}
IInterB : IBaseInter {}
IInterC : IBaseInter {}

I need to call a function with one of those Interface types, decided at runtime. Basically I want to do something like this

Type interfaceType; 
if (condition == 1){
    interfaceType = typeof(IInterA);
}
if (condition == 2){
    interfaceType = typeof(IInterB);
}
if (condition == 3){
    interfaceType = typeof(IInterC);
}

var result = MyFunction<interfaceType>("foo");

public T MyFunction<T>(string val)
{
    // do some work
    ...
    return ClassICantModify.FunctionICantModify<T>(resultOfWork);
}

This causes the following complaint though : 'invokerType' is a variable but used like a type

Is it possible to do what I want? I need to use interfaceType in this way a bunch of times, so i'd like to save the type in a variable as opposed to creating result in each of those ifs. All the other examples i've found online of trying to do something similar seem to be of creating a class, not calling a function, and don't seem to work.

user3715648
  • 1,498
  • 3
  • 16
  • 25

1 Answers1

1

you can add a method to your class like this:

public object MyNonGenericFunction(Type t,string value)
        {
            return this.GetType().GetMethod("MyFunction").MakeGenericMethod(t).Invoke(this,new object[]{value});
        }

and you can use it like:

var result= MyNonGenericFunction(interfaceType,myStringValue);

here an article from Microsoft about how to call non-generic method from generic method using MakeGenericMethod ... https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodinfo.makegenericmethod?view=netframework-4.8

OMR
  • 11,736
  • 5
  • 20
  • 35