Search code examples
c#oopinheritancebase-class

In C#, is inheritance from a method possible?


Now, if the title sounds weird to you, consider this code, I was reviewing today (simplified):

public class MyService(
    IHttpClientFactory httpClientFactory) : 
        BaseService(), // WTF? a Method?
        IMyService
{
    //no explicit constructor, has default constructor
    //.... 
}

This actually compiles! The MyService class inherits something from BaseService, apparently a method, and implements the IMyService interface.

BaseService is an abstract class, only defining some static objects and some literal strings:

public abstract class BaseService
{
    public static List<MaintenanceWindow> RegisteredMaintenanceWindows = new List<MaintenanceWindow>();
    protected static string CERT_SERVICE_URI = "https://cert.example.com";
    public static string DEFAULT_DOMAIN = "default.example.com";
    // ....
}

What does MyService inherit here?

  • There is no actual method in the base class
  • Does it inherit the (default) constructor?

I have never observed this kind of C# inheritance, and also these inheritance docs from Microsoft do not mention it.


Solution

  • The class is not inheriting a method.

    Notice that MyService has a primary constructor. After the class name, there is a parameter list (IHttpClientFactory httpClientFactory).

    As with all constructors, the primary constructor needs to call a base class constructor before it can do anything. The () after BaseService is the syntax to call a base class constructor in the primary constructor. The () is a(n empty) parameter list.

    It is as if you have declared a constructor like this

    public MyService(IHttpClientFactory httpClientFactory): base() {
        // ...
    }
    

    Similar to regular constructors, explicitly calling the base class constructor is not necessary here, because BaseService has a parameterless constructor. : base() can be omitted in the above code snippet. Similarly, class MyService(...): BaseService is also valid.

    If the base class has no parameterless constructor, then it is necessary to add the (...) after BaseService, and pass the required parameters.

    For more info, see the Initialise Base Class section.