Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting class and call hidden base constructor

Tags:

c#

Consider in AssemblyOne

public class A
{
    internal A (string s)
    { }
}

public class B : A
{
    internal B (string s) : base(s)
    { }
}

In AssemblyTwo

public class C : B
{
    // Can't do this - ctor in B is inaccessible
    public C (string s) : base(s)
}

Obviously this is a code smell, but regardless of if being a bad idea is it possible to call the ctor of B from the ctor of C without changing AssemblyOne?

like image 786
Ryan Avatar asked Feb 26 '23 11:02

Ryan


2 Answers

Ignore Assembly Two for the moment. You would not be able to instantiate an instance of class C, because it inherits from B, which there are no public constructors for.

So if you remove the inheritance issue from Class C, you'd still have an issue creating instances of class B outside of B's assembly due to protection levels. You could use reflection to create instances of B, though.

For the purposes of testing, I altered your classes as follows:

public class A
{
    internal A(string s)
    {
        PropSetByConstructor = s;
    }

    public string PropSetByConstructor { get; set; }
}

public class B : A
{
    internal B(string s)
        : base(s)
    {
        PropSetByConstructor = "Set by B:" + s;
    }
}

I then wrote a console app to test:

static void Main(string[] args)
    {
       System.Reflection.ConstructorInfo ci = typeof(B).GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[0];
        B B_Object = (B)ci.Invoke(new object[]{"is reflection evil?"});

        Console.WriteLine(B_Object.PropSetByConstructor);


        Console.ReadLine();
    }

I would not recommend doing this, its just bad practice. I suppose in all things there are exceptions, and the exception here is possibly having to deal with a 3rd party library that you can't extend. This would give you a way to instantiate and debug, if not inherit.

like image 85
Jonathan Bates Avatar answered Mar 08 '23 06:03

Jonathan Bates


This is not possible, even with reflection.

If a class has no accessible constructors, there is no way to create a class that inherits it.

like image 29
SLaks Avatar answered Mar 08 '23 06:03

SLaks