Question How can I pass multiple type variables to generic type variable T?

tobias233

New member
Joined
Nov 12, 2015
Messages
1
Programming Experience
5-10
Hello :joyous:,
I am doing C# for a half year now. Today I want to call a method like this in a class with the name "A":

C#:
public T TheMethod<T>(IRestResponse response)    {
      ...
    }

At compile time, T isn't known.
C#:
var theType = typeof(B);

So I tried the following:
C#:
var gMethod= typeof(A).GetMethod("TheMethod");
var rExecution = gMethod.MakeGenericMethod(theType);
var params = ...;
var result = (C)rExecution.Invoke(new A(), new object[] { params });

The code above is okay for execute the method in these form:
C#:
public C TheMethod<T>(IRestResponse response)    {
      ...
    }

But now I want to execute the method so:
C#:
public List<T> TheMethod<T>(IRestResponse response)    {
      ...
    }

How can I handle this? Thanks for help!
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
857
Location
Norway
Programming Experience
10+
If what you're trying to make 'result' a List<T> kind of variable that you can code for at compile time then I think the only solution is to use an interface, for example constrain T as IReturn and return a List<IReturn>, which you then can cast to.
Or you can cast result as System.Collections.IList if the type of item does not matter.
 
Top Bottom