reflection / casting

C

cv

Hi, I want to create an object from a class I load from an assembly.
Then I want to cast that object to a class (an interface) 'known' to the
program in order to pass it to other methods that work with that interface.

The casting is invalid but I can't see why, as the class I load from the
assembly really is of the type I cast it to.

Command a = (Command) t.GetConstructor(new
Type[0]).Invoke(System.Reflection.BindingFlags.Public,null,null,null);

What can be the cause of the cast being invalid? I tried to cast it to
almost everything that might be possible. I didn't find any examples on
the Internet that do really cast the object.
I know I can invoke a method on the returned object by using Invoke(..
but that's not really the purpose.

Maybe somewhat clearer:

ConstructorInfo ci = t.GetConstructor(new Type[0]);
object o = ci.Invoke(System.Reflection.BindingFlags.Public,null,null,null);
Command a = (Command) o;

-> Invalid cast exception

t.FullName
-> program.shell.textualshell.commands.command

Type tt = o.getType();
tt.FullName
-> program.shell.textualshell.commands.command

I'm totally in the dark here..
Please do not hesitate to ask additional information if necessary.
Thanks in advance.
 
R

Richard A. Lowe

Ok, here's your checklist:
- You have a declared interface in an assembly
- The class you are trying to create by reflection implements that interface
(i.e. has a declaration like: public class Whatever : IMyInterface)
- The very same interface (same assembly it's declared in) is referenced in
the program creating the object via reflection, and that is the interface
you try to cast it to.

If all these things are true then you class should be castable to the known
interface. If however, for example, your class has methods that match a
declared interface, but it does not explictly implement the interface, you
cannot cast it. In that case you will have to use delegates or reflection
to invoke the methods.

Richard
 
J

Jon Skeet [C# MVP]

cv said:
Hi, I want to create an object from a class I load from an assembly.
Then I want to cast that object to a class (an interface) 'known' to the
program in order to pass it to other methods that work with that interface.

Sounds like your problem is the one in
http://www.pobox.com/~skeet/csharp/plugin.html

If it isn't, could you post a short but complete program which
demonstrates the problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 

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