Problem statement: If C# Interface and abstract class in a program, both contains only method declaration (C# source code shown below) then what would be your best choice between interface and abstract class and why? Note that abstract class will not contain any other method implementation.
Below is the Interface and abstract class declaration and both have only function declaration.
//Interface
interface IInterface
{
void func();
}
//Abstract class
abstract class AbstractClass
{
abstract public void func();
}
Answer: Best choice is an Interface in this scenario
This is true that in above interface and abstract class design both offers contract with derived classes to implement func() method and off course we can use any of them without any issue, but, Interface would be the best choice because of following reasons.
Reasons:
- We know that C# does not support multiple inheritance and we cannot extend multiple classes but multiple Interfaces can be extended. So, if we are choosing the Abstract class we are blocking derived classes a chance to extend some other important class.
- In this design you and I only know that Abstract class will have contracts only. Consider a large project and decided to use this abstract class instead of Interface. At some later point of time if new programmer comes, there are chances that he may implement some other method in it and can start using somewhere in the project. So, he may violet our design. Or else we have to take extra overhead to document it. If we have use Interface, he cannot violet the design even by mistake.
NOTES: C# program example: Getting same result using Interface or Abstract class.
Using C# Interface:
//Interface
interface IShape
{
void draw();
}
//Derived
class Circle : IShape
{
public void draw()
{
Console.WriteLine("Drawing Circle");
}
}
//Test class
class ShapeGame
{
public void drawShape(IShape shape)
{
shape.draw();
}
}
class Program
{
static void Main(string[] args)
{
IShape circle = new Circle();
ShapeGame g = new ShapeGame();
g.drawShape(circle);
}
}
Using C# Abstract Class:
//Abstract class
abstract class Shape
{
abstract public void draw();
}
//Derived
class Circle : Shape
{
public override void draw()
{
Console.WriteLine("Drawing Circle");
}
}
//Test class
class ShapeGame
{
public void drawShape(Shape shape)
{
shape.draw();
}
}
class Program
{
static void Main(string[] args)
{
Shape circle = new Circle();
ShapeGame g = new ShapeGame();
g.drawShape(circle);
}
}
For both program Output will be same:
Drawing Circle