Search code examples
c#inheritanceinterface

Add common method to classes inheriting from a C# Interface?


I have an interface such as this one:

    public interface ITestInterface
    {
        int a { get; set; }

        void DoSomething();
    }

Some of my classes are deriving from this interface:

    public class OneClass : ITestInterface
    {
        public int a { get; set; }

        public void DoSomething()
        {
            Console.WriteLine(this.a.ToString());
        }
    }

    public class AnotherClass : ITestInterface
    {
        public int a { get; set; }

        public void DoSomething()
        {
            Console.WriteLine((this.a * 2).ToString());
        }
    }

Since I now need a (large) common method on all classes derived from my interface, I was trying to provide an additional base class for that:

 public class MyBaseClass
    {
        public void LargeCommonMethod()
        {
            Console.WriteLine((this.a * 3).ToString()); // no 'a' on base class
        }
    }

This clearly doesn't work because the base class would also need to implement my interface in order to know about that a field.

I am now asking myself what the best approach would be here:

  • make MyBaseClass inherit from ITestInterface?
  • set LargeCommonMethod() to protected and provide all internal data it uses via arguments? (There's actually a lot of these..)
  • skip the interface all along and replace it with an abstract base class?
  • ...?

Solution

  • C# 8 provides a feature precisely for this scenario.

    • Your classes all implement an interface
    • You want to add a method to the interface
    • You don't want a breaking change to all of the existing classes. If you add a method to the interface all of the classes will break unless you find some way to add the method to all of them. (That includes modifying them all to inherit from a new base class.)

    That feature is default interface methods.

    You can add your method and a default implementation to the interface:

    public interface ITestInterface
    {
        int a { get; set; }
    
        void DoSomething();
    
        void LargeCommonMethod()
        {
            Console.WriteLine((this.a * 3).ToString());
        }
    }
    

    Your existing classes that implement the interface will not break. When cast as the interface, you'll be able to call the method which is defined in the interface. You can still modify any class to provide its own implementation, overriding the interface's default implementation.

    For the method to be available the object must be cast as the interface - ITestInterface.

    A lot of developers - including myself - found this to be an odd feature. But this is the scenario it's for.

    Some documentation

    The most common scenario is to safely add members to an interface already released and used by innumerable clients.