Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# cast a class to an Interface List

I'm trying to load some .dll files dynamically. The Files are Plugins (self-written for now) which have at least one class that implements MyInterface. For each file I'm doing the following:

    Dictionary<MyInterface, bool> _myList;

    // ...code

    Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
    foreach (Type type in assembly.GetTypes())
    {
        var myI = type.GetInterface("MyInterface");
        if(myI != null)
        {
            if ((myI.Name == "MyInterface") && !type.IsAbstract)
            {
                var p = Activator.CreateInstance(type);
                _myList.Add((MyInterface)p, true);
            }
        }
    }

Running this causes a cast exception, but I can't find a workaround. Anyway I am wondering why this doesn't work at all. I'm looking for a solution in .NET Framework 3.5.

Another thing that happened to me was getting null in p after running the following at the point before adding a new entry to _myList in the code above:

var p = type.InvokeMember(null, BindingFlags.CreateInstance, null,
                          null, null) as MyInterface;

This code was the first attempt on loading the plugins, I didn't find out why p was null yet. I hope someone can lead me to the right way :)

like image 790
Phil Avatar asked Aug 08 '12 15:08

Phil


1 Answers

There's much easier way to check if your type can be casted to your interface.

Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
foreach (Type type in assembly.GetTypes())
{
    if(!typeof(MyInterface).IsAssignableFrom(type))
        continue;

    var p = Activator.CreateInstance(type);
    _myList.Add((MyInterface)p, true);
}

If IsAssignableFrom is false, there's something wrong with your inheritance, which is most likely cause of your errors.

like image 120
Serg Rogovtsev Avatar answered Sep 18 '22 00:09

Serg Rogovtsev