InvalidCastException when creating an instance using assembly.CreateInstance
Posted
by Yossi Dahan
on Stack Overflow
See other posts from Stack Overflow
or by Yossi Dahan
Published on 2010-04-21T07:23:09Z
Indexed on
2010/04/21
7:53 UTC
Read the original article
Hit count: 515
c#
|reflection
I'm looking for an explanation for the following - I have an assembly I'm loading using
Assembly assembly = Assembly.LoadFrom(filename);
I then loop on all the types in the assembly, and wish to try and find out if a type implements a particular interface and if so I want an instance of that type, I've tried several things which did not work, but when I fell back to the most basic (and probably inefficient) way, I realised there's something more fundamental I don't understand -
foreach (Type t in assembly.GetTypes())
{
foreach (Type i in t.GetInterfaces())
{
if (i.FullName == pluginInterfaceType.FullName)
{
object o = assembly.CreateInstance(t.ToString());
IInterface plugin = (IInterface)o;
That last line causes an InvalidCastException, despite the fact that the type created definitely implements that interface.
Further more - if I use Activator.CreateInstance instead of Assembly.CreateInstance (which I don't want to do), casting to the interface works just fine.
© Stack Overflow or respective owner