Darren Young
Darren Young

Reputation: 11090

Reflection usage for creating instance of a class into DLL

I have the following code:

var type = typeof(PluginInterface.iMBDDXPluginInterface);
var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

Type t = types.ElementAt(0);
PluginInterface.iMBDDXPluginInterface instance = Activator.CreateInstance(t) as PluginInterface.iMBDDXPluginInterface;
TabPage tp = new TabPage();

tp = instance.pluginTabPage();

The class within the dll implements the PluginInterface and the Type in the code above, is definately the correct class/type, however when I try to create an instance through the interface i get an error message saying:

Object reference not assigned to an instance of an object.

Anybody know why?

Thanks.

Upvotes: 3

Views: 677

Answers (2)

abatishchev
abatishchev

Reputation: 100238

Anyway

TabPage tp = new TabPage();
tp = instance.pluginTabPage();

makes no sense.

Do:

TabPage tp = instance.pluginTabPage();

Also do next:

Type type = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .FirstOrDefault(p => type.IsAssignableFrom(p));
if (type != null)
{
    // create instance
}

or (my preferred way):

from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.GetTypes()
where !type.IsInterface && !type.IsAbstract && typeof(ITarget).IsAssignableFrom(type)
select (ITarget)Activator.CreateInstance(type);

Upvotes: 3

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

Try looking at the type in reflector. Maybe the constructor takes arguments that you are not correctly passing to Activator.CreateInstance .

Upvotes: 1

Related Questions