Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

dll

activator

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?

like image 725
eranj Avatar asked Feb 27 '26 05:02

eranj


1 Answers

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)

like image 153
jgauffin Avatar answered Mar 01 '26 18:03

jgauffin