2

I'm loading a .NET assembly dinamically via reflection and I'm getting all the classes that it contains (at the moment one). After this, I'm trying to cast the class to an interface that I'm 100% sure the class implements but I receive this exception: Unable to cast object of type System.RuntimeType to the type MyInterface

MyDLL.dll

public interface MyInterface
{
    void MyMethod();
}

MyOtherDLL.dll

public class MyClass : MyInterface
{
    public void MyMethod()
    {
        ...
    }
}

public class MyLoader
{
    Assembly myAssembly = Assembly.LoadFile("MyDLL.dll");
    IEnumerable<Type> types = extension.GetTypes().Where(x => x.IsClass);

    foreach (Type type in types)
    {
        ((MyInterface)type).MyMethod();
    }
}

I have stripped out all the code that is not necessary. This is basically what I do. I saw in this question that Andi answered with a problem that seems the same mine but I cannot anyway fix it.

Community
  • 1
  • 1
Stefano
  • 3,213
  • 9
  • 60
  • 101

1 Answers1

3

You are trying to cast a .NET framework object of type Type to an interface that you created. The Type object does not implement your interface, so it can't be cast. You should first create a specific instance of your object, such as through using an Activator like this:

// this goes inside your for loop
MyInterface myInterface = (MyInterface)Activator.CreateInstance(type, false);
myInterface.MyMethod();

The CreateInstance method has other overloades that may fit your needs.

Daniel Gabriel
  • 3,939
  • 2
  • 26
  • 37