Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I call the base constructor when deriving from ServiceBase?

Tags:

c#

.net

Microsoft .NET documentation for the System.ServiceProcess.ServiceBase class constructor says:

If you override the base class constructor, you should explicitly call it in the constructor of your derived class.

In Using Constructors in the Microsoft C# Programming Guide, it says:

In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly.

So do I need to call the base constructor explicitly or not, and why?

like image 497
Boric Avatar asked Jul 02 '12 19:07

Boric


People also ask

Is Base constructor always called?

The base constructor will be called for you and you do not need to add one. You are only REQUIRED to use "base(...)" calls in your derived class if you added a constructor with parameters to your Base Class, and didn't add an explicit default constructor.

Are constructors called automatically?

A constructor in C++ is a special method that is automatically called when an object of a class is created.

Does C# automatically call base constructor?

In C#, when we create an instance of the child class, the base class's default constructor automatically gets invoked by the compiler.

Does child class call parent constructor C#?

Child calls their parent In addition, when initializing a Child object, C# will automatically call the default constructor of the parent Base class first, after that constructor of the subclass will be called.


1 Answers

It doesn't matter. These compile to the same IL:

public class Service1 : ServiceBase
{
    public Service1() : base() { }
}
public class Service1 : ServiceBase
{
    public Service1() { }
}

I don't know why ServiceBase recommends explicitly calling it. I'd go with the other suggestion, since it seems to make more sense.

like image 129
Tim S. Avatar answered Sep 23 '22 07:09

Tim S.