I’d like to invoke a method that returns a struct, using the MethodInfo.Invoke method. However, the returned variable’s type of this metod is object, which cannot be cast to a struct.
(found that, as well as the suggestion to switch from struct to class, here: http://msdn.microsoft.com/en-us/library/b7tch9h0(VS.90).aspx )
So how could I cast the (value) result of the invoked method to it’s proper type?
(I’ve tried simple cast as well, but it threw an InvalidCastException)
Here are some chunks of my code:
public class MyInvokedClass
{
public struct MyStruct
{ ... };
public MyStruct InvokedMethod()
{
MyStruct structure;
...
return structure;
}
}
public class MyInvokingClass
{
// Same structure here
public struct MyStruct
{ ... };
static void Main(string[] args)
{
...
MethodInfo methodInfo = classType.GetMethod(methodName);
MyStruct result = (MyStruct)methodInfo.Invoke(classInstance, null);
// the line above throws an InvalidCastException
}
}
Thank you all!
The cast fails because they are different types, more specifically one is
MyInvokedClass.MyStructand the other isMyInvokingClass.MyStruct.When
InvokedMethodgets called theMyStructrefers to the type nested inside theMyInvokedClass, but the when the cast is performed(MyStruct)refers to the type nested inside theMyInvokingClass.You could use
MyInvokedClass.MyStructinsideMyInvokingClassto refer to the correct struct, but even better is just to have oneMyStructtype.You may find useful to read more about declaration space:
C# Basic Concepts—Declarations