Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multilevel inheritance constructor in C#

Is there a way in C# to call the grandfather's constructor? Let's say I have:

public class A
{
   public A(parameterX x)
   {
      doSomething();
   }
}

public class B : A
{
   public B(parameterX x) : base(x)
   {
      doSomethingElse();
   }
}

And then I have:

public class C : B
{
}

And I want the constructor in C to call the constructor in A, what can I use for this? Is there something like:

public C(parameterX x) : base : base(x)

Or how can I just call the constructor in A from C?

Thanks.

like image 220
lander16 Avatar asked Jun 03 '26 16:06

lander16


2 Answers

You cannot call a grandparent class' constructor.
However, you don't need to either, since the base class already does.

When you write public C(parameterX x) : base(x), it will call B(x), which will in turn call A(x).

In general, since your base class' constructor will always call its base constructor (your grandparent), it wouldn't make sense to be able to explicitly call the grandparent constructor, since that would end up constructing it twice.

like image 115
SLaks Avatar answered Jun 05 '26 04:06

SLaks


Although I don't really understand what is that you are trying to do and you probably can come up with a better actual design, you can probably achieve what you need by adding another constructor in B that takes the Bar parameter as A, but do nothing in it simply calling A(Bar) constructor, that way when you do C(bar) : base(bar) it will go to B and then to A. Ugly as hell.

like image 45
Francisco Soto Avatar answered Jun 05 '26 04:06

Francisco Soto



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!