Casting problem when use Reflection for object construction

R

Roman Muntyanu

Hi all,

I created object of MyClass : ISomeInterface

Then I created object of this class using reflection mechanism.

ISomeInterface instance =
(ISomeInterface)constructorInfo.Invoke(new Object [0]);

This casting works fine. But When I try

MyClass instance1 = (MyClass)constructorInfo.Invoke(new Object [0]);

I'm getting "Specified cast is not valid" exception.
I tried such an experiment

ISomeInterface instance2 = new MyClass();
MyClass instance1 = (MyClass)instance2;
And this casting works fine. So I found that there is difference how I
created the object of MyClass.

Could someone help to resolve this issue ?

Thank you very much in advance

Roman
 
J

Jon Skeet [C# MVP]

Roman Muntyanu said:
I created object of MyClass : ISomeInterface

Then I created object of this class using reflection mechanism.

ISomeInterface instance =
(ISomeInterface)constructorInfo.Invoke(new Object [0]);

This casting works fine. But When I try

MyClass instance1 = (MyClass)constructorInfo.Invoke(new Object [0]);

I'm getting "Specified cast is not valid" exception.
I tried such an experiment

ISomeInterface instance2 = new MyClass();
MyClass instance1 = (MyClass)instance2;
And this casting works fine. So I found that there is difference how I
created the object of MyClass.

Could someone help to resolve this issue ?

See http://www.pobox.com/~skeet/csharp/plugin.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top