Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is explicitly calling base() in derived constructors optional?

Tags:

c#

.net

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?

like image 539
Kumar Avatar asked Mar 26 '12 15:03

Kumar


1 Answers

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).

like image 125
BrokenGlass Avatar answered Sep 17 '22 16:09

BrokenGlass