I have a method that returns byte[] but for now would like to avoid using generics on the method to supply the return type. I currently pass a parameter into this method that has the details of the type of the data that will be serialized to the byte[] return result.
Question:
How do I perform a dynamic cast of the result of .Invoke()?
I’m using reflection to call a method on a class the output of this is object and this result needs to be cast.
The Code:
public byte[] SomeMethod(/* some params */)
{
MethodInfo info = /* ... */ .GetMethod(methodToCall);
//Here I want to perform a dynamic cast:
return (info.Invoke(classToCall, methodParams)).Serialize();
//if I was to just have the method fixed to a type it would look like:
return (info.Invoke(classToCall, methodParams) as SomeType).Serialize();
//NOTE: .Serialize() is just my own extension method
}
What I have tried without success:
//with returnType as a string
var dynamicType = Type.GetType(returnType);
(info.Invoke(classToCall, methodParams) as dynamicType).Serialize();
Also some other variations with typeof(), GetTypeHandle, .ReflectedType
Am I missing something simple and/or obvious, or am I just trying to do something strange/silly?
Additional note: the SomeMethod is an override of a method of a class hence not wanting to have the method support a generic type.
It is a common misunderstanding that the cast operator really does anything in this situation. You either want to convert from the type that
Invokereturned to another type, or it already is the type you want it to be even thoughInvokeis declared to returnobject.Since I don’t think you want to convert anything, you have to first recognize that the return value of calling
Invokelike this:the
resultwill be a variable of typeobjectbut the value in that variable will already be the type you want to cast it to. You just don’t know exactly what it is. And you need to know what it is to callSerialize.Now, you have this extension method, or set of overloaded extension methods that operate on a compile time specified initial
thisparameter. One of them matches the type of the return value of theInvokecall.In order to choose which of these methods to call, you need to use reflection again to get a
MethodInfomatching the right type and just call yourSerializemethod. It might help if it weren’t an extension method because now you have no easy way to look up the extension method the same way the compiler does at compile time only. Extension method matching is extremely laborious and not suited to dynamic invocation.Instead, if you want to use reflection a second time to call
Serialize, without having a giant switch statement, then you need to have a utility class with all theSerializemethods as public overloads within that class. At least that is one way to approach the problem.