Any class that inherits an interface is considered of that type, so it makes it easy to create implementations that do different things. More importantly it makes it easier to test. Lets say you have an Interface called IMyInterface:
public interface IMyInterface
{
void PrintMessage(string message);
}
You can then create two different classes that both implement the interface:
public class ConcreteClassA : IMyInterface
{
public void PrintMessage(string message)
{
Console.WriteLine("My implementation here: " + message);
}
}
class MyConcreteClassB : IMyInterface
{
public void PrintMessage(string message)
{
Console.WriteLine("My other implementation here: " + message);
}
}
This means that when I implement the code like this:
class Program
{
static IMyInterface myInterface;
static void Main(string[] args)
{
myInterface = new ConcreteClassA();
myInterface.PrintMessage("hello");
myInterface = new MyConcreteClassB();
myInterface.PrintMessage("good day");
}
}
I dont create a dependency for class Program on either ConcreteClassA or MyConcreteClassB. If I make any subsequent changes to either of these classes then it doesnt affect class Program because it only deals with the interface. Its a great way to abstract your code, and its something I did not realise after reading up on it. Can an abstract class provide the same type of “abstraction”? Not really, and for a several reasons, the first being that you cannot create an instance of an abstract class and secondly you would have to expose the implementation details of the classes that inherit the abstract class.