Ioanna
Ioanna

Reputation: 1377

How to convert value types returned by the MethodInfo.Invoke method, to their proper type?

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!

Upvotes: 2

Views: 3742

Answers (3)

João Angelo
João Angelo

Reputation: 57718

The cast fails because they are different types, more specifically one is MyInvokedClass.MyStruct and the other is MyInvokingClass.MyStruct.

When InvokedMethod gets called the MyStruct refers to the type nested inside the MyInvokedClass, but the when the cast is performed (MyStruct) refers to the type nested inside the MyInvokingClass.

You could use MyInvokedClass.MyStruct inside MyInvokingClassto refer to the correct struct, but even better is just to have one MyStruct type.

You may find useful to read more about declaration space:

C# Basic Concepts—Declarations

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

To solve your problem, move the structure out of the classes:

public struct MyStruct
{ ... };

public class MyInvokedClass
{
    public MyStruct InvokedMethod()
    { 
        MyStruct structure;
        ... 
        return structure; 
    }
}

public class MyInvokingClass
{
    static void Main(string[] args)
    { 
        ...
        MethodInfo methodInfo = classType.GetMethod(methodName);
        MyStruct result = (MyStruct)methodInfo.Invoke(classInstance, null); 
    }
}

Upvotes: 2

LukeH
LukeH

Reputation: 269628

You have two different types: MyInvokedClass.MyStruct and MyInvokingClass.MyStruct.

The method you're invoking presumably returns MyInvokedClass.MyStruct and you're attempting to cast it to a MyInvokingClass.MyStruct. You're hitting the InvalidCastException because those are two completely different types.

Upvotes: 3

Related Questions