How to create or call the protected constructor of an abstract class using reflection?

I am trying to call or instantiate an abstract class using reflection. It is possible. This is what I tried, but I get the error "Unable to instantiate abstract class".

Type dynType = myTypes.FirstOrDefault(a => a.Name == "MyAbstractClass"); ConstructorInfo getCons = dynType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null); object dynamicInstance = getCons.Invoke(null); 

EDIT: Can I access the properties of this abstract class using reflection?

+4
source share
4 answers

Calling a constructor in an abstract class is equivalent to trying to instantiate an abstract class, which is impossible (you cannot create instances of abstract classes).

What you need to do is create an instance of the derived class and declare its constructor so that it calls the base constructor, as in:

 public class DerivedClass : AbstractClass { public DerivedClass() : base() { .... } } 

Full example:

 public abstract class Abstract { public Abstract() { Console.WriteLine("Abstract"); } } public class Derived : Abstract { public Derived() : base() { Console.WriteLine("Derived"); } } public class Class1 { public static void Main(string[] args) { Derived d = new Derived(); } } 

Result of this

 Abstract Derived 
+2
source

You cannot instantiate an abstract class without even using reflection.

If you need an instance, either:

  • remove the abstract modifier from the class.
  • If you cannot do this (for example, if the class is in a private library), define a subclass that inherits from the abstract class and instantiates this class.
0
source

You cannot instantiate an abstract class. However, you can use inheritance and use implicit casting

 Derived derived = new Derived(); Abstract abstract = derived; 

Through implicit casting, you can handle a derived instance, such as an instance of a base class.

From MSDN

 The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. 

See MSDN for help.

0
source

As mentioned in all previous answers: its impossible to create an abstract class.

Another important note: for an instance of an instance by reflection, you should use Activator.CreateInstance , but not a constructor call.

 object dynamicInstance = Activator.CreateInstance(yourType, yourArguments); 

Creating an object is a slightly more complicated process than just calling the constructor. This requires the allocation of the required amount of memory, and only then configure the object itself by calling the constructor.

0
source

All Articles