So, I need to call a third party method, that has a signature like this
ThirdPartyMethod<T>(IEnumerable<T> items)
My problem is I don't know the type of my object at compile time.
At compile time I have this
IEnumerable myObject;
Type typeOfEnumerableIHave;
Sooo..can reflection help me out here somehow?
for simplicity sake, pretend I have a method like this
void DoWork(IEnumerable items, Type type)
{
//In here I have to call ThirdPartyMethod<T>(IEnumerable<T> items);
}
You could try something like this:
The code creates a list instance of the generic type "type" (by using MakeGenericType). Your item elements are then copied to the list and the third party method is called via relection (note the "MakeGenericMethod" call to ensure that the method has the same type parameter as the method argument.
Since you have
IEnumerable myObject;
and signature likeThirdPartyMethod<T>(IEnumerable<T> items)
you are able to useCast()
:If you don't know the
T
type at the compile time you should provide it at runtime.Consider you third-party library looks like this
if you have following
you can get generic methods
ThirdPartyMethod
andCast
at the runtimeFinally you call the method: