Late Binding an Interface

G

Guest

How can i load an interface from a dll using System.Reflection?

I can see how its possible to do this on methods, properties in a class. You
create an instance of the class and use the invoke method.

Type t = Type.GetType("MyAssembly.MyClass");
Object obj1 = Activator.CreateInstance(t);
obj1.GetType().InvokeMember("MyMethod",BindingFlags.Default,null,obj1,new
object[]{});

But you cannot create instances of interfaces, so how can you late bind
methods/properties in an interface....?

thanks




An interface however cannot create instances, so
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

AFAIK this is not possible, what do you want to do?

An interface is like the opposite of what you want to do, with an interface
you are early binding the methods/properties an instance will have, with
late binding/reflection you just "discover" the interface at runtime.


cheers,
 
F

Frisky

I am not sure what your asking. Could you elaborate more.

You can't create instances of interfaces. You can create instances of
classes that implement interfaces. And you can get the the interface from a
class instance.

For example, (from your example)

Type myType = Type.GetType("MyAssembly.MyClass");
IMyInterface myInterface = Activator.CreateInstance(myType) as
IMyInterface;
myInterface.DoThatVoodoo(thatYouDo, soWell);

Does this help?

Frisky
 
G

Guest

....therin lies my answer!! thank you, everyone.

I was skipping a step, that's why i was having problems. What i need to do
is to perform late binding on a class that implements my interface.

aha!
 
N

Nicholas Paldino [.NET/C# MVP]

CodeRazor,

If you have a reference to the interface definition, then you can create
an instance of your type (through the Activator class) and then just cast
the instance to the interface type. For this reason, the interface types
are usually defined in an assembly outside of the implementation, so that it
can be shared by the implementation, and the code using the implementation.

Hope this helps.
 

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