Ensuring a base constructor is called?

J

Josh Valino

If I have a base class that has one constructor, is the only way that that
constructor will get called be by having no constructors in my derived
classes or explicitly calling base() in my derived constructors?
Illustration:

abstract class whatever
{
public whatever()
{
//code here I want to run
}
}

class derivedClass : whatever
{
public derivedClass() : base()
{
}
}

That ":base()" is necessary in this case, correct? I guess what I'm more
looking for is some mechansism that will ensure that code in my base classes
is always executed when a derived object is instantiated. I'm mostly trying
to compensate for a behavioral problem here, fearing that other developers
won't remember to put the ": base()" on their constructors. :-/

TIA,

Josh
 
J

Jon Skeet [C# MVP]

On Jul 30, 5:08 pm, "Josh Valino" <no spam please> wrote:

That ":base()" is necessary in this case, correct?

No. If you don't specify either :base(...) or :this(...) then the
compiler effectively inserts :base() for you.
I guess what I'm more
looking for is some mechansism that will ensure that code in my base classes
is always executed when a derived object is instantiated. I'm mostly trying
to compensate for a behavioral problem here, fearing that other developers
won't remember to put the ": base()" on their constructors. :-/

They don't need to - the base class constructor will always be called.

Jon
 
I

Ignacio Machin ( .NET/ C# MVP )

If I have a base class that has one constructor, is the only way that that
constructor will get called be by having no constructors in my derived
classes or explicitly calling base() in my derived constructors?
Illustration:

abstract class whatever
{
  public whatever()
  {
    //code here I want to run
  }

}

class derivedClass : whatever
{
  public derivedClass() : base()
  {
  }

}

That ":base()" is necessary in this case, correct?  

No, the compiler will add a call for you.
I guess what I'm more
looking for is some mechansism that will ensure that code in my base classes
is always executed when a derived object is instantiated.  I'm mostly trying
to compensate for a behavioral problem here, fearing that other developers
won't remember to put the ": base()" on their constructors.  :-/

the base will always be constructed, if you do not especify one
version, the compiler will try to call the default (no paremeter) if
not exist you get an error
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top