Two fundamental concepts in Object Oriented Programming (OOP), interfaces and abstraction help achieve extensibility, modularity, and loose coupling in your code. You might find these terms doing almost the same thing when you try it out at once, but they differ from design and implementation perspective in a software.
In this article, we will deep dive in the key differences between interfaces and abstraction in C#, and when to use each.
This article assumes you have knowledge or at least know what inheritance is.
Just to add a recap:
Inheritance in C# is a process of child class getting some or all the properties possessed by a parent class.
Now, let’s get started!
Abstraction
Hiding certain details and showing what’s important to the user is termed as ‘Abstraction’ in C#. Abstraction can be achieved by two ways:
Abstract classes
Interfaces
Think of a secret recipe shared only with chefs in a restaurant (the base class) and not with customers (outside world). All chefs (inherited classes) know and use the recipe, but it’s not revealed to anyone else.
We will discuss Interface later in this article, but for now, let’s understand what are abstract classes and abstract method that falls under Abstraction
Abstract class
Normally, we can create objects out of a normal class, but this is not the case with Abstract class.
It is a restricted class than cannot be used to create objects.
It must be inherited from another class in order to access it.
Abstract method
Abstract methods are bound to Abstract classes. Meaning, such methods can only be used in an abstract classes.
They do not contain body. The body is provided by the derived class.
An abstract class can have both abstract and regular methods:
But what happens when you try to create an object of the Animal class:
You can see the red line beneath when object is created. Pay attention to the message upon hovering the red line.
Cannot create an instance of the abstract type or interface ‘Animal’
The rule is, if you want to access anything from the abstract class, some other class must inherit this class.
In other words, it must be inherited from another class in order to access the abstract class.
Here is the full example what I meant by the above sentence
Output
Explanation
An abstract class
Animal
` is created. This acts as a base class or the parent class.An abstract method
animalSound()
is created of type void because we don’t need to return anything from it as of now.There is regular method
burp()
.Then we have a
Dog
class that inherits the parent classAnimal
.The
override keyword is used with
to override the values mentioned in thisanimalSound()
.Finally, we have
Main()
that is an entry point to a console project which has an instance ofDog
` class created. You can access both the methods — the base class one as well as the derived class one.
What happens when you don’t implement a method defined in base class?
Try removing the animalSound()
` from Dog
` class and see what happens.
Key point to notice:
Since the
burp()
` does not haveabstract
` keyword in it, it is not mandatory for a derived class to inherit.
Use an Abstract class when:
You expect future classes to extend your base class.
You have a base class with default behavior that some subclasses will share.
You want to achieve security where you wish to hide certain details and only show the important details of an object.
Interfaces
Another way to achieve abstraction in C# is with Interfaces.
An interface
is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies):
Starting C# 8, we can also add implementation to the interface methods, but we will just stick to the original concept and understand the latter approach later.
The above is just an example, but it’s a good practice to write all the interfaces starting with a letter “I” as you would easily recognize this class as Interface and not a normal class.
Members of an interface are
abstract
andpublic
by default.Interfaces cannot contain fields, but can contain properties and methods.
Similar to Abstract classes, in order to access the interface methods, the interface must be implemented by another class. Now when I say “Implement” I mean “Inherit”.
You don’t need “override” keyword while implementing an interface
Output
Explanation
An interface
IAnimal
is created. Notice it’s not justAnimal
, butIAnimal
.A
Dog
class inheritingIAnimal
withanimalSound()
` implementation of base class.An instance of
Dog
created and the method is called.
Key points to notice
It is not possible to create object of an interface.
To implement an interface, you must inherit all the methods in it.
Interface cannot contain a constructor as it cannot be used to create objects.
When To Use Interfaces?
Multiple Inheritance — C# does not support multiple inheritance. Meaning a class can only inherit one class at a time. It cannot inherit multiple classes. To solve this, Interface comes to the rescue!
You want to provide maximum flexibility and decoupling between classes.
You want to define behavior that can be shared across unrelated classes.
To read more about Multiple Inheritance, I have another detailed article which you can refer
https://buymeacoffee.com/rohanraobhb/the-diamond-problem-c-how-interfaces-solve-it
Key Differences Between Interface and Abstraction
1. Implementation
Abstract Class: Can contain both complete (non-abstract) and incomplete (abstract) methods, allowing for partial implementation.
Interface: Contains only declarations, no implementation. All methods are abstract by nature.
2. Multiple Inheritance
Abstract Class: C# supports single inheritance, meaning a class can only inherit from one abstract class.
Interface: A class can implement multiple interfaces, allowing for multiple inheritance of behavior.
3. Fields and Properties
Abstract Class: Can define fields and properties, and provide implementations for properties.
Interface: Cannot have fields. Interfaces can define properties but only in terms of their signature (no implementation).
4. Constructor
Abstract Class: Can have constructors and destructors to initialize fields or resources.
Interface: Cannot have constructors or destructors.
5. Access Modifiers
Abstract Class: Methods can have access modifiers (
public
,protected
,internal
, etc.), giving you more control over accessibility.Interface: All members are
public
by default, and no access modifiers are allowed.
Conclusion
Both interfaces and abstract classes play crucial roles in C# programming, but they serve different purposes. Abstract classes are about code reuse and inheritance, allowing you to define partial implementations that can be shared among subclasses. Interfaces, on the other hand, are about defining contracts that any class can implement, regardless of where it fits into the inheritance hierarchy.
Found this useful?
If you enjoyed this article and found it helpful, consider supporting my work by buying me a coffee! Your support helps me create more valuable content like this and keeps me fueled for the next deep dive into coding topics. 😊☕
🔗 https://buymeacoffee.com/rohanraobhb
Thank you for your reading!