Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base Base Constructor C# initialization

Tags:

c#

inheritance

A simplified scenario. Three clases, GrandParent, Parent and Child. What I want to do is to make use of the GrandParent and Parent constructor to initalize a Child instance.

class GrandParent ()
{
    public int A {get; protected set;}
    public int B {get; protected set;}

    public GrandParent (int a, int b);
    {
        A = a;
        B = b;
    }
}

class Parent : GrandParent ()
{
    public Parent () {}
}

Child Class, were the problem occurs.

class Child : Parent ()
{
    public int C {get; protected set}

    public Child (int c) // here I want it to also call the GrandParent (int a, int b)
                         // before calling Child (int c)
    {
        C = c;
    }
}

Child = new Child (1,2,3);

What I want is that the variables a,b and c to get 1,2 respectively 3 as values. I know I can solve it by simply adding A = a and B = b to the Child constructor.

Is this possible? If so how?

I begun looking at base () however it looked like it was only able to access the Parent class and not the GrandParent.

Thanks in advance.

PS. If it has been asked before, I apologize in advance, I did not find anything.

Quick edit: I am trying to make the solution as easy as possible to work with, to develop further.

like image 622
Emz Avatar asked May 08 '26 00:05

Emz


1 Answers

You can only invoke the constructors to the direct superclass. The direct superclass needs to expose the options that you need. It can safely do this with a protected constructor.

like image 98
Daniel A. White Avatar answered May 10 '26 14:05

Daniel A. White