Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Instance using base constructor

For reasons out of the scope of the question, I'm needing to dynamically create an instance of a child class that inherits from a base class, calling a constructor that doesn't exist with an argument passed to the base class constructor

Using example below: should create an instance of ExampleClass sending value to argument1 of BaseClass.

class BaseClass
{
    public BaseClass()
    {

    }
    public BaseClass(string argument1)
    {
        //...
    }
}

class ExampleClass : BaseClass
{
    public ExampleClass()
    {
    }
}

EDIT: I made another topic where I explain the source or my problem: Entity Framework DbContext dynamic instatiation with custom Connection String

like image 719
Tuk Avatar asked Aug 03 '26 17:08

Tuk


1 Answers

If I understand it correct you can't modify ExampleClass but need to create an instance of it that uses a different constructor for the base class?

I belive there is not build in way in the framework to achive it, even with reflection. So your goal should be to bypass the framework and use MSIL

However, this topic I found on SO looks promissing.

Dynamically create type and call constructor of base-class

like image 199
Jürgen Steinblock Avatar answered Aug 05 '26 07:08

Jürgen Steinblock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!