Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a second level base class constructor

In C#, I have a class, foo, that inherits from class bar, which in turn inherits from class foobar.

In the foo constructor, I want to call the foobar constructor directly, not from a call to the bar constructor. I tried something like this:

 public foo(int i): base : base(i)

Obviously this does not work. How would you make it work, without passing through the bar constructor?

like image 933
jbkkd Avatar asked Sep 14 '25 05:09

jbkkd


1 Answers

You can't, as you cannot skip the initialization of bar. You have to create a constructor in bar that passes your argument through. The reason is that it's bar's responsibility to decide how it wants its base class to be constructed. (The construction of the base class is part of bar's implementation, and one of the principles of object-orientation is encapsulation -- hiding implementation to the outside.)

like image 155
JohnB Avatar answered Sep 16 '25 18:09

JohnB