2

I have recently started working with winservices and I stumbled upon this link about winservice ctor and it talks about "overriding" the ServiceBase constructor. Feeling stupid i googled what that means and stumbled upon this. Question: What do they actually mean by saying "overriding" in the docs?To chain back explicitly to a ServiceBase ctor?

  • 2
    The documentation is a bit misleading. It simply means to provide a constructor for your new class. A constructor is not virtual, so you cannot override it (a word that already has a meaning in the C# language). – Lasse V. Karlsen Feb 26 '19 at 09:55
  • It's very poor phrasing of a *general* rule in .NET. That if you have any constructors in your class, you have to ensure they chain back to a constructor in your base class. Since this class only has one constructor, there aren't many choices of which constructor to chain back to. (Insert all standard defaults around `:object` and `base()`). So I'm not sure why they called it out at all. – Damien_The_Unbeliever Feb 26 '19 at 10:05

2 Answers2

1

I don't really agree with what MS says. ServiceBase has an empty default constructor which will automatically be called so the statement that you have to override it (which is not true as well, I'd be overloading instead of overriding) is not really true. However, what I guess they meant is to call the base constructor like this

public class MyService : ServiceBase {
    public MyService(var something) : base(){

    }
}

which is the same as

public class MyService : ServiceBase {
    public MyService(var something){

    }
}

/edit: In theory, if you'd overload (not override) the base constructor, you'll have to explicitly call it.

public class ServiceBase{
    public ServiceBase(){

    }

    public ServiceBase(var something) {

    }
}
public class MyService : ServiceBase {
    public MyService(var something)
        : base(something) 
    {

    }
}

However, overloading the ServiceBase constructor is not possible because the class is not marked as partial.

devsmn
  • 1,031
  • 12
  • 21
  • Thanks, I suppose they just wanted to tell us to do the "minimum" ("The minimum you need to implement in the constructor for a class inherited from ServiceBase is to set the ServiceName on your component.") which I actually do not do. – Nichita Cebotari Feb 26 '19 at 10:46
0

MS just states that you should call the base constructor if you derive from ServiceBase (like this)

class MyService:ServiceBase
public MyService : base() {
.. custom code ..
}

This will call the base constructor in addition to your new .ctor. Have a look here for "overriding" .ctor: C# - Making all derived classes call the base class constructor

Sebastian
  • 379
  • 1
  • 7