CloudyMarble
CloudyMarble

Reputation: 37576

Call the base Constructor in the Constructor of the subclass

Is it possible to call the base Constructor at spicific point in the constructer of the subclass like:

public class SuperClass
{
  public SuperClass(Object myObject)
  {
     // init some values ...
  }
}

public class SubClass: SuperClass
{
  public SubClass(): base(Object myObject)
  {
     //Check some preconditions
     base(myObject);
     // Do some other stuff
  }
}

Upvotes: 2

Views: 818

Answers (3)

Danil
Danil

Reputation: 1893

The right syntax is

public class SubClass: SuperClass
{
  public SubClass(object myObject): base(myObject)
  {

  }
}

Here is link of using constructors. It is impossible to call it in ctor's body directly.

Upvotes: 1

Servy
Servy

Reputation: 203827

No, it's not possible.

One way to achieve this behavior you could extract the contents of the base constructor out into a method and then call that method from the subclass.

Another less closely tied method would be to just not use inheritance here. It's possible that this is a situation in which composition would make more sense. (It's impossible to say for sure without knowing more information though.)

Upvotes: 3

spender
spender

Reputation: 120498

No, because at //Check some preconditions you'd have a partially constructed object. This would lead to all sorts of problems.

Upvotes: 1

Related Questions