Search code examples
c#inheritanceinterfacebase-classinterface-implementation

Whether to extend interface, when base class already extends same interface


In C#, as shown in the code snippet below, is it correct/proper to extend the interface IFoo when declaring the class A, knowing that the class BaseClass extends the interface IFoo? Is it necessary to specify the interface IFoo here, and is it best practice?

class A : BaseClass, IFoo
{
}

Might be a silly question, but what is the appropriate practice in this case?


Solution

  • If the BaseClass is Inherited from IFoo it is totally unnecessary to use IFoo in your Class A.

    Check the image below (Resharper is used for this recommendation)

    enter image description here


    Special thanks to @InBetween

    If interface reimplementation is the case, re-defining interface on child class has use case.

    interface IFace
    {
        void Method1();
    }
    class Class1 : IFace
    {
        void IFace.Method1()
        {
            Console.WriteLine("I am calling you from Class1");
        }
    }
    class Class2 : Class1, IFace
    {
        public void Method1()
        {
            Console.WriteLine("i am calling you from Class2");
        }
    }
    
    int main void ()
    {
        IFace ins = new Class2();
        ins.Method1();
    }
    

    This method returns i am calling you from Class2

    whereas,

    interface IFace
    {
        void Method1();
    }
    class Class1 : IFace
    {
        void IFace.Method1()
        {
            Console.WriteLine("I am calling you from Class1");
        }
    }
    class Class2 : Class1
    {
        public void Method1()
        {
            Console.WriteLine("i am calling you from Class2");
        }
    }
    
    int main void ()
    {
        IFace ins = new Class2();
        ins.Method1();
    }
    

    returns I am calling you from Class1