In this article, We are going to discuss the “difference between Abstract class and Interface in C#” with simple examples. This is one of the most frequently asked questions in almost every C# dot net interview.
Table of Contents
- 1 What is Abstract class in C#?
- 2 What is Interface in C#?
- 3 Differences Between Abstract Classes and Interfaces in C#
- 4 C# Abstract class Vs Interface
- 5 When to use an Interface in C#?
- 6 When to use Abstract class Instead of Interface in C#?
- 7 What’s new about the interface in C# 8.0
- 8 Important Key Points About An Interface In C# 8.0
- 9 FAQs
- 9.1 Q: Can you instantiate an interface in C#?
- 9.2 Q: Why can’t we instantiate an abstract class in C#?
- 9.3 Q: Can an interface have a constructor?
- 9.4 Q: Why abstract class is used in C# .NET?
- 9.5 Q: Can we declare the abstract method as static?
- 9.6 Q: Can you inherit multiple interfaces in C#?
- 9.7 Q: Is it compulsory for the abstract class to have at least one method as an abstract?
- 9.8 Q: When to use an abstract class vs interface in C#?
- 9.9 Q: When should I use an abstract class, and when should I use an interface?
- 10 Summary:
What is Abstract class in C#?
An abstract class in C# is a class that cannot be directly instantiated using the new
keyword and always acts as a base class for other classes.
Abstract classes are created using the abstract keyword. They provide a common structure for derived classes to follow. The key characteristics of abstract classes in C# include:
- Abstract classes in C# can contain abstract methods without actual code implementation. These methods must be implemented in the derived classes.
- Abstract classes can also have non-abstract methods with actual code. Derived classes can inherit and, if needed, override these methods.
- Unlike other classes, abstract classes in C# can’t be sealed. It means other classes can extend them further.
- Abstract classes can have constructors, but you can’t create objects from them directly. Instead, objects of the abstract class are created using derived class constructors.
Here is an example of an abstract class in C#:
using System;
// Define an abstract class called 'Shape'
abstract class Shape
{
// An abstract method for calculating area, to be implemented by derived classes.
public abstract double CalculateArea();
// A non-abstract method with a default implementation.
public void DisplayArea()
{
Console.WriteLine("Area: " + CalculateArea());
}
}
// Create a derived class 'Circle' that inherits from 'Shape'
class Circle : Shape
{
private double radius;
// Constructor to initialize the radius
public Circle(double r)
{
radius = r;
}
// Implement the abstract method to calculate the area of a circle.
public override double CalculateArea()
{
return Math.PI * radius * radius;
}
}
class Program
{
static void Main()
{
// Create an instance of the 'Circle' class
Circle circle = new Circle(5.0);
// Calculate and display the area of the circle
circle.DisplayArea();
}
}
Output:
//Result:
Area: 78.5398163397448
Code Explanation:
- We define an abstract class
Shape
with an abstract methodCalculateArea()
that should be implemented by derived classes. It also has a non-abstract methodDisplayArea()
with a default implementation. - We create a derived class
Circle
that inherits fromShape
. It provides an implementation for theCalculateArea()
method. - In the
Main
method, we create an instance of theCircle
class, set its radius, and then call theDisplayArea()
method to calculate and display the area of the circle.
What is Interface in C#?
An interface in C# is a blueprint for defining a contract that specifies a set of methods, properties, events, or indexers a class must implement.
Unlike abstract classes, an interface contains only method and property signatures but no method implementations.
Here are the key characteristics of an interface in C#:
- Purely Abstract: Interfaces contain only method signatures, properties, events, or indexers without implementations.
- Multiple Inheritance: A class can implement multiple interfaces, which allows inheriting behaviors from several sources.
- Contract Enforcement: When a class implements an interface, it’s bound to fulfill a contract by providing members (method, properties etc.) implementation with the correct signatures.
- Polymorphism: Interfaces enable polymorphism, allowing objects of different classes to be treated as instances of the interface type.
An Interface is similar to an abstract class but cannot be directly instantiated and can’t have constructors. Interfaces are used when different classes need to share a common behavior without having the same base class.
Here is a simple code example that demonstrates the use of an interface in C#:
using System;
// Define an interface named 'IDrawable'
interface IDrawable
{
void Draw();
}
// Create a class 'Circle' that implements the 'IDrawable' interface
class Circle : IDrawable
{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Program
{
static void Main()
{
Circle circle = new Circle();
circle.Draw(); // Calls the 'Draw' method implemented in the 'Circle' class.
IDrawable drawable = circle; // Polymorphism: Treating 'circle' as an 'IDrawable'.
drawable.Draw(); // Still calls the 'Draw' method in the 'Circle' class.
}
}
Output:
Drawing a circle
Drawing a circle
Code Explanation:
In this example, the IDrawable
interface defines a contract with a single method Draw()
. The Circle
class implements this interface by providing its own implementation of the Draw()
method. This allows us to call the Draw()
method on a Circle
object and also treat the Circle
object as an IDrawable
object.
Differences Between Abstract Classes and Interfaces in C#
Below are the key differences between abstract classes and interfaces in C#:
- In C#, Abstract classes can provide both method implementations and declarations, Whereas Interfaces only contain method and property declarations without implementations.
- Abstract classes can have constructors. At the same time, interfaces do not support constructors because they cannot be instantiated.
- Abstract class members can have various access modifiers (public, protected, etc.), whereas Interface members are implicitly public and cannot have access modifiers.
- In C#, an abstract class can have both fields and properties, while an interface supports properties but not fields, and they are implicitly abstract.
- In C#, an abstract class is used to share and reuse common code among related classes. Meanwhile, an interface works more like a contract, ensuring that derived classes of unrelated types must implement the data members defined in the interface.
- Abstract classes allow partial method implementation, whereas Interfaces require full method implementation in derived classes.
- Abstract classes support single-class inheritance, while Interfaces allow multiple-interface inheritance.
C# Abstract class Vs Interface
An abstract class can provide a partial implementation and can have both abstract and non-abstract methods, while an interface only defines method signatures without any implementation. A class can inherit from only one abstract class but can implement multiple interfaces.
In Short, An abstract class allows you to create functionality that subclasses can implement or override. An interface, on the other hand, only allows you to define functionality rather than implement it.
- The abstract class and interface are used to achieve abstractions. (In C#, Abstraction is the process of defining the essential details to call methods without exposing the implementation details.)
- If complex functional units are not your objective, an interface might be more appealing. Use abstract classes if you want to extend the class hierarchy in the future
Both abstract class and interface have their own advantages and disadvantages. So, without further ado, let us take a closer look at the abstract class and interface in depth.
Tabular Comparison between the abstract class and the interface.
Sr.No. | Abstract Class | Interface |
---|---|---|
01. | In C#, An Abstract class can have public, private, or protected class members. | However, every method, property, and event contained within an Interface is always public by default. |
02. | An abstract class in C# can contain constructors. | An interface in C# can’t contain a constructor |
03. | Abstract classes do not support multiple Inheritance | On the other side, the Interface supports multiple Inheritance in C#. |
04. | A class can be inherited by only one abstract class. | A class can inherit by multiple interfaces. |
05. | An abstract class in C# can be fully implemented, partially implemented, or not implemented at all. | An interface contains only the signatures of methods, properties, events, or indexers not the implementation. |
06. | Abstract class members such as methods or properties can be defined as abstract, virtual, static, or sealed. | Interface members can’t be defined as abstract, virtual, static, or sealed. |
07. | An abstract class can contain both declaration and Implementation of methods. | An interface is used when you only need the signature of a method and not the implementation. |
08. | An abstract class can contain fields and constants. | An interface cannot have fields. |
09. | If multiple implementations of methods are of the same kind and use common behavior, then it’s better to use an abstract class. So that the common implementation code does not need to be repeated in each of the descending or subclasses. | If multiple unrelated classes only share method signatures and have different implementations of methods, then it is better to use Interface. |
10. | An abstract class can contain the main method in C#. | An interface can’t contain the main method. |
When to use an Interface in C#?
Below is the list of reasons for using the interface in C#.
- A C# Interface allows for multiple Inheritance. A class, however, cannot inherit from more than one abstract class.
- You can achieve loose coupling by using the Interface.
- An interface can be used when you want the derived classes to fully implement all of the methods introduced in the base class.
- Abstraction can be achieved via interfaces.
- Interface Allows you to decouple a method’s definition from its inheritance hierarchy.
- An interface can be used to achieve polymorphic behavior, a single method of an Interface can have multiple redefinitions into multiple classes of unrelated types. Here, every derived class is free to provide its own implementation.
- Interfaces are best suited to achieve Dispose Pattern by defining an IDisposable interface.
- An Interface doesn’t contain a constructor, which helps to prevent extra roundtrip when creating an object of the derived class through the reference pointer of the interface.
- An Interface can be a great choice when we want to loop through a collection for example by using an IEnumerable interface.
-
Your application will be easier to test and maintain if you use an interface. It helps to define a contract, or agreement, between your application and other objects. This agreement specifies the methods, fields, properties, and events an object exposes.
You should use an interface if you want a contract on some behavior or functionality to be strictly followed by the subclass or struct. If you use interfaces, you must implement all of the methods in the subclass that extends the interface.
- Interfaces may be a good choice to decouple your application’s code from specific implementations as different classes can implement methods differently.
- You can also use an interface if you want to simulate inheritance for structs because structs cannot inherit from another struct or class in C#.
When to use Abstract class Instead of Interface in C#?
This is one of the most frequently asked questions in C# dot-net interviews. Most developers are still not completely sure of the right answer. The following examples are used to illustrate these concepts.
- The Abstract classes offer default functionality for the derived classes.
- An abstract class is a great choice if you want to share a common code among several closely related classes. It acts as a base class and provides the common code implementation to the derived classes.
- An abstract class can be used to achieve versioning of the components because by adding the new functionality to the base class all the derived classes will get updated automatically. An interface on the other hand can’t be modified once created and inherited by the classes. We must create a new interface if we want to add a new method to the interface.
- You can go with the abstract class if you wanted to provide the default implementation to all the subclasses.
- The Abstract class allows code reusability.
- You can use an abstract class if we don’t want to implement all of the methods in a derived class but only some of them in a parent class.
Example 2: Abstract class in C#
Let’s create a simple program for an abstract class.
using System;
namespace AbstractClassDemo
{
// Abstract class
public abstract class Bank
{
// Abstract method
public abstract void CashWithdraw(double amount);
//field
protected double balance;
// Concrete method
public void Balance()
{
Console.WriteLine($" Total Balance: {this.balance}");
}
}
// Derived class "HsbcBank" inheriting base "Bank" class
public class HsbcBank : Bank
{
// Constructor
public HsbcBank(double amount)
{
this.balance = amount;
}
// Implementing base class method
public override void CashWithdraw(double amount)
{
if (amount > this.balance)
{
Console.WriteLine(" Insufficient funds in bank account");
return;
}
Console.WriteLine($" Withdrawing Cash ${amount} from HSBC Bank.");
Console.WriteLine($" Remaining Balance : {this.balance - amount}");
}
}
// Derived class "CityBank" inheriting base "Bank" class
public class CityBank : Bank
{
// Constructor
public CityBank(double amount)
{
this.balance = amount;
}
// Implementing base class method
public override void CashWithdraw(double amount)
{
if (amount > this.balance)
{
Console.WriteLine(" Insufficient funds in bank account");
return;
}
Console.WriteLine($" Withdrawing Cash ${amount} From City Bank.");
Console.WriteLine($" Remaining Balance : {this.balance - amount}");
}
}
class Program
{
static void Main()
{
Console.WriteLine("***** Abstract class example in C# *****");
Bank bank = new HsbcBank(5000);
bank.Balance();
bank.CashWithdraw(300);
Console.WriteLine();
bank = new CityBank(10000);
bank.Balance();
bank.CashWithdraw(500);
Console.ReadLine();
}
}
}
What’s new about the interface in C# 8.0
C# 8.0 changed a lot of things about the interface and most of the folks are still not aware of these new changes.So let’s try to explore the new features of the Interface introduced in C# 8. We will try to understand how we can use these features in our projects with simple examples.
Default Interface Methods Introduced In C# 8.0
The Default interface method which is also known as the virtual extension method is a new feature introduced in C# 8.0
It allows an Interface to add a method with implementation without breaking the existing functionality. Before C# 8 an interface was allowed to contain only (signature) the declaration part of methods, properties, events, or indexers, but now after C# 8.0 interface can contain both the declaration and the implementation.
Example of the default interface method
The following is a simple program to illustrate the concept of the default interface method in C# 8
using System;
namespace DefaultInterfaceMethodDemo
{
// Default Interface Method In C# 8.0
interface IDefaultInterface
{
// This "ShowMessage" method is having only the declaration part.
void ShowMessage(string text);
// Default interface method with both declaration and definition (Implementation).
//Now Interface members can be public, private, or protected
public void DefaultInterfaceMethod()
{
Console.WriteLine("Default method of interface!");
}
}
// A class that implements
// the "IDefaultInterface" interface.
class MyClass : IDefaultInterface
{
// Providing implementation
// part of the "ShowMessage" method
void IDefaultInterface.ShowMessage(string text)
{
Console.WriteLine(text);
}
}
class Program
{
static void Main()
{
IDefaultInterface myClass = new MyClass();
// Calling default interface method
myClass.DefaultInterfaceMethod();
myClass.ShowMessage("Hello World!");
Console.ReadLine();
}
}
}
// Output
// Default method of interface!
// Hello World!
In the above program, we can see that we have provided the implementation for the method “DefaultInterfaceMethod” in the interface itself. Here, “MyClass” does not need to implement this method.
Here, we call the “DefaultInterfaceMethod” method with the help of the “IDefaultInterface” interface reference variable. If we try to call the “DefaultInterfaceMethod” method with the class object we will get the following compile-time error.
Change the IDefaultInterface to MyClass, as shown in the below screenshot.
The above sample program produces the compile-time error because the “MyClass” does not contain a member “DefaultInterfaceMethod”.
This is proof that the inherited class “MyClass” does not know anything about the default Interface method.
The default interface methods will only work or be accessible if the class is contextually treated as an interface.
To access the default method of the interface, we must upcast the “myClass” object to the “IDefaultInterface” interface as follows.
static void Main()
{
MyClass myClass = new MyClass();
//Upcasting to the interface to access the default method
((IDefaultInterface)myClass).DefaultInterfaceMethod();
}
// Output:
// Default method of interface!
Access Modifiers In Interface C# 8.0
Prior to C# 8.0, interface members could only have an implicitly default public access modifier. Modifiers such as private
, public
, protected
, internal
, virtual
, and abstract
were not permitted within an interface.
Here you can read more in details about the access modifiers in C#.
Example of Access Modifiers In An Interface
using System;
namespace AccessModifiersInInterface
{
// Access Modifiers In Interface C# 8.0
interface IInterface
{
// Default Interface method is private by default.
private void PrivateDefaultMethod()
{
Console.WriteLine(" Private Default Method Of Interface!");
}
// Public Default Method
public void PublicDefaultMethod()
{
Console.WriteLine(" Public Default Method Of Interface!");
}
//Protected Default Method
protected void ProtectedDefaultMethod()
{
Console.WriteLine(" Protected Default Method Of Interface!");
}
//virtual method
virtual void VirtualDefaultMethod()
{
Console.WriteLine(" Virtual Default method Of Interface!");
}
//abstract method having the only declaration
abstract void AbstractDefaultMethod();
// static method
static void StaticDefaultMethod()
{
Console.WriteLine(" Static Default Method Of Interface!");
}
}
// A class that implements
// the "IInterface" interface.
class MyClass : IInterface
{
// Providing implementation
// part of the abstract method
void IInterface.AbstractDefaultMethod()
{
Console.WriteLine(" Abstract Default Method Of Interface!");
}
}
class Program
{
static void Main()
{
Console.WriteLine("***** Access Modifiers In Interface C# 8.0 *****");
IInterface obj = new MyClass();
//obj.PrivateDefaultMethod(); // inaccessible due to its protection level
//obj.ProtectedDefaultMethod(); // inaccessible due to its protection level
obj.PublicDefaultMethod();
obj.VirtualDefaultMethod();
obj.AbstractDefaultMethod();
IInterface.StaticDefaultMethod();
Console.ReadLine();
}
}
}
// Output:
//*****Access Modifiers In Interface C# 8.0 *****
// Public Default Method Of Interface!
// Virtual Default method Of Interface!
// Abstract Default Method Of Interface!
// Static Default Method Of Interface!
Important Key Points About An Interface In C# 8.0
- An interface can have only the declarations part that is no longer true. After
C# 8.0
, the Interface can implement code for methods, properties, events, or indexers. - In C# 8, interface members can have access modifiers such as
private
,public
,protected
,internal
,virtual
,abstract
,override
,static
, andsealed
. - In C# 8, the Interface can have fields, but only if they are static.
- In C# 8, An interface can have default methods but the derived class inherited by the Interface does not know anything about the existence of the default methods also class does not contain the implementation code of the default method defined in the Interface.
- The default interface members are not inherited in the derived class in C# 8.
To learn more about Interface, please refer to this article: C# 10 new features
FAQs
Q: Can you instantiate an interface in C#?
An interface can’t be directly instantiated in C#. However, we can access the data members of an interface by creating an object of the implementing class and then assigning the object to the reference variable of the interface it implements.
The following is a simple example to understand.
Q: Why can’t we instantiate an abstract class in C#?
No, we can’t create an instance of an abstract class because it is an incomplete class. All the members of an abstract class are not fully implemented but partially implemented. We can create an object of a fully implemented class only.
Q: Can an interface have a constructor?
No, the Interface can’t have constructors as there are no instance data members (fields) in the interface for initializing through the constructor. Constructors are generally invoked during object creation and we are not allowed to create an instance of the interface so, it doesn’t make sense to have a constructor in an interface.
Q: Why abstract class is used in C# .NET?
An abstract class is generally used to provide a template, blueprint, or a set of common rules that all the derived classes must follow and implement.
The purpose of the abstract class is to provide the default functionality to all the derived classes. It can contain both abstract and concrete methods that should be open for overriding by the derived classes.
Q: Can we declare the abstract method as static?
No, We can’t declare an abstract method as static because overriding is not possible with static methods.
Q: Can you inherit multiple interfaces in C#?
Yes, A class can inherit (implement) multiple interfaces in C#.
Q: Is it compulsory for the abstract class to have at least one method as an abstract?
No, it is not necessary to declare an abstract method inside an abstract class.
Q: When to use an abstract class vs interface in C#?
The quick answer is that you can use an abstract class to design functionality that subclasses can implement or override. On the other hand, you can only specify the functionality with an interface, not implement it. A class can extend just one abstract class, but it can extend several interfaces.
Q: When should I use an abstract class, and when should I use an interface?
You should use an abstract class when you want to provide a common base with some shared implementation for related classes. Abstract classes are suitable when you have a hierarchy of classes that share some common behaviors or state.
Use an interface when you want to define a contract for unrelated classes to implement shared behavior.
In essence, choose an abstract class for a is-a
relationship (inheritance) and an interface for a can-do
relationship (implementation of behaviors).
References: InfoWorld- Abstract class Vs Interface
Summary:
In this article, we learned about the ‘difference between the Abstract class and Interface in C#‘ with simple examples. Also, we learned the new features in an Interface introduced in C# 8.
I hope you found this post useful in learning about Abstract class and Interface in C#. Your comments, suggestions, and constructive criticism are much appreciated.
Recommended Articles:
- C# Tutorial
- Understanding Interface in C# with Examples
- Understanding C# Abstract Class
- SOLID Design Principles in C#: A Complete Example
- Singleton Design Pattern in C#: A Beginner’s Guide with Examples
- Top 50 C# Interview Questions and Answers For Freshers and Experienced in 2022
- Collections in C#–Queue, Stack, ArrayList, and Hashtable
- WCF vs Web API: Top 10 Differences Between WCF and Web API
- C# Array vs List: When should you use an array or a List?
- Generic Delegates in C# With Examples
- Serialization and Deserialization in C# with Example
- Sealed Class in C# with examples
- C# Enum | How to Use enumeration type in C#?
- Properties In C# with examples
- Multithreading in C#
- IEnumerable Interface in C# with examples
- C# List Class With Examples
- C# Struct vs Class
- C# Dictionary with Examples
- Fields vs Properties In C#
- Readonly vs const in C#
We would love to hear your thoughts on this post. Please leave a comment below and share it with others.
- Difference Between Array And ArrayList In C#: Choosing the Right Collection - May 28, 2024
- C# Program to Capitalize the First Character of Each Word in a String - February 21, 2024
- C# Program to Find the Longest Word in a String - February 19, 2024