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?
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.
A constructor in C++ is a special method that is automatically called when an object of a class is created.
In C#, when we create an instance of the child class, the base class's default constructor automatically gets invoked by the compiler.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With