Kumar
Kumar

Reputation: 11369

Is explicitly calling base() in derived constructors optional?

All the code examples always use base() as follows

class A 
{ 
    public A() 
    {
        Console.Writeline("A");
    } 
}

class B : A 
{ 
    public B():base() {} 
}

e.g. http://msdn.microsoft.com/en-us/library/hfw7t1ce%28v=vs.71%29.aspx

whereas as i discovered recently

class A 
{ 
    public A()
    {
        Console.Writeline("A");
    } 
}

class B : A 
{ 
    public B() {} 
}

also prints A

Q - is it a new "feature" or is it bad form not to call base() in derived class constructors and will add to my bad karma and cause problems later ?

or

can calling base() safely be ignored?

Upvotes: 5

Views: 959

Answers (5)

pfries
pfries

Reputation: 1758

You don't need to call base() from your constructor when both the parent and the child have a implicit or explicit parameterless constructor. That will happen by default, and no, it's not new. Typically, you would use the base() method to say which parent constructor you are calling and to pass arguments from the child's constructor to the parent's.

Try it with arguments in your constructor to see how it works.

Upvotes: 0

Botz3000
Botz3000

Reputation: 39670

calling base() is not required. Default base constructors are called automatically unless you explicitly call another one. It's a matter of personal preference i think, kinda like prepending this before accessing instance fields.

Upvotes: 1

FishBasketGordo
FishBasketGordo

Reputation: 23142

The default constructor will get called whether or not you explicitly call it with : base(). It's a matter of style, but the prevailing convention is to leave it off unless you're calling a specific, parameterized base constructor.

Upvotes: 3

GazTheDestroyer
GazTheDestroyer

Reputation: 21261

You only need to use base if

1) You need to pass variables down to the base constructor.

2) You need to specify which base constructor to use.

Other than that you can safely leave it out. The default base constructor will be called.

Upvotes: 6

BrokenGlass
BrokenGlass

Reputation: 161012

No that's not new - if you do not explicitly call a base constructor, the default constructor will be called by default.

Adding this yourself I would consider just "noise", the compiler will do it for you already so you don't have to. You should only call a base constructor if you need a specific overload other than the default constructor (that means you do need to have a base constructor call though if the base class does not provide a default constructor).

Upvotes: 7

Related Questions