Search code examples
c#dllactivator

C# Activator.CreateInstance() drops "Cannot create an abstract class" exception


I am trying to dynamicly load .DLL file and run one of its methods (actually there is only one method..) but the Activator.CreateInstance method drops an "Cannot create an abstract class" exception This is my code:

Assembly assembly = Assembly.Load(DLLByteArray);
//Type typeToExecute = assembly.GetType("ClassLibrary1.Class1");
//last line was replaced with the next one to ensure that the name is correct.
Type typeToExecute = assembly.GetTypes()[0];
Object instance = Activator.CreateInstance(typeToExecute);

the class deceleration if needed: "public static unsafe class Class1".

Does anything in the .DLL class code can cause this kind of exception?


Solution

  • What you are trying to do:

    Assembly assembly = Assembly.Load(DLLByteArray);
    Type typeToExecute = assembly.GetTypes()[0];
    typeToExecute.GetMethod("TheMethod").Invoke(null, theArguments);
    

    That will invoke a static method with an object[] (theArguments) containing all method arguments

    The other solution is simply to remove the static keyword from the class and the method (which will make your current code work)