ayilmaz ayilmaz - 3 months ago 45
C# Question

Create a list of objects from dynamically loaded dll on runtime

I have a dll that is loaded on runtime. I am trying to create instances of each Type from dynamically loaded dll on runtime, and add these instances into a List. All classes in the dll are based from AYClass, so they should be added into the List succesfully. But I am having such an error like below

Exception thrown:
'Microsoft.CSharp.RuntimeBinder.RuntimeBinderInternalCompilerException' in Microsoft.CSharp.dll

Additional information: An unexpected exception occurred while binding a dynamic operation


My code is like below...

Assembly assembly = Assembly.LoadFrom(@"D:\Library\CurrencyData.dll");
List<AYClass> listObjects = new List<AYClass>();
foreach (Type type in assembly.GetExportedTypes())
{
if (type.BaseType.ToString().Contains("AYClass"))
{
dynamic c = Activator.CreateInstance(type);
listObjects.Add(c); // ******* Exception is thrown here
}
}


What should I do to fix this?

Answer

Why do you use dynamic when you know the base type? Don't do that. Use var instead:

Assembly assembly = Assembly.LoadFrom(@"D:\Library\CurrencyData.dll");
List<AYClass> listObjects = new List<AYClass>();
foreach (Type type in assembly.GetExportedTypes())
{
    if (type.BaseType.ToString().Contains("AYClass"))
    {
        var c = (AYClass)Activator.CreateInstance(type);
        listObjects.Add(c);
    }
}

In general C# is a type safe language, so using dynamic should be exceptional. Also be sure, that in your dynamic loaded dll and in your "loader" they use the exact same base-class. In any other case casting the instance will fail.

Furthermore you could replace this line: if (type.BaseType.ToString().Contains("AYClass")) with comparing the type and not its name. This is not very safe, because a class with the same name can be declared in different assemblies and or namespaces in the same assembly.