Shouman Shouman - 2 months ago 16
C# Question

Interface and abstract class in this case

In case I want any class inherits/implements some methods which is better an interface or an abstract class contains these abstract methods only and acts as an interface. I know the difference between the interface and the abstract class well but in this case do the two have the same function or there are different something?

I think we can feel free to use one of them but still I take the side of interface because my aim is to enforce any class to implement these methods and it is the job of interface.

Answer

I agree an abstract class with no concrete behavior seems a little pointless so I would favour an interface.

Abstract classes are far more useful when bringing together some common behavior that cannot be overridden along with some elements that can eg) template methods

public abstract class Base
{
    public void TemplateMethod()
    {
        AbstractMethod1();
        AbstractMethod2();
    }

    public abstract void AbstractMethod1();
    public abstract void AbstractMethod2();
}


public class Concrete : Base
{
    public override void AbstractMethod1()
    {
        Console.Write("Override Abstract Method 1");
    }

    public override void AbstractMethod2()
    {
        Console.Write("Override Abstract Method 2");
    }
}

public class Main
{
    public Main()
    {
        var concrete = new Concrete();
        concrete.TemplateMethod();
    }
}
Comments