views:

47

answers:

2

Hi, I have a few classes in the class library (separate assembly). I referenced it to my project and I want to initialize one specific class from that library. I know only its name. All of the classes implements one interface. And here comes the problem.

My code so far:

using MyLibrary;
...
IMyInterface dll = Activator.CreateInstance("MyLibrary", "MyLibrary.NameOfClass") as IMyInterface;

But dll is always null. Any ideas?

Thanks

UPDATE

I remove reference to the library and rewrite that code to:

Assembly a = Assembly.Load("MyLibrary");
Type type = a.GetType("MyLibrary.SKClass");
IMyInterface obj = Activator.CreateInstance(type) as IMyInterface;

but obj is null.

If I checked library types with a.GetExportedTypes(), SKClass is there. So why is this code still returning null?

+2  A: 

var assembly = Assembly.LoadFile(@"full\path\to.dll");

var type = assembly.GetType("Full.Namespace.Type");

var object = Activator.CreateInstance(type);

Danny Varod
thanks it's working.
daemonsvk
A: 

Why aren't you using this...?

Assembly a = Assembly.Load("ClassLibrary1"); Interface1 i = a.CreateInstance("ClassLibrary1.ClassName") as Interface1;

Is it necessary that you have to use Activator...?

Nilotpal Das