Introduction
In C#, both Abstract Classes and Interfaces are used to achieve abstraction and define a contract for derived classes. They are core concepts in object-oriented programming and are widely used in real-world application development. However, they serve different purposes and understanding the difference between abstract class and interface in C# is important for writing clean, maintainable, and scalable code.
This article explains abstract class vs interface in C# with simple examples, real-world use cases, and a clear comparison table.
What is an Abstract Class in C#?
An abstract class in C# is a class that cannot be instantiated directly. It is designed to be inherited by other classes and can contain both abstract methods (without implementation) and concrete methods (with implementation).
Key Features of Abstract Class
Can contain both abstract and non-abstract methods
Can have constructors
Can have fields (variables)
Supports access modifiers (private, protected, public)
A class can inherit only one abstract class (single inheritance)
Example of Abstract Class
abstract class Vehicle
{
public string Brand;
public void Start()
{
Console.WriteLine("Vehicle is starting...");
}
public abstract void Drive();
}
class Car : Vehicle
{
public override void Drive()
{
Console.WriteLine("Car is driving...");
}
}
class Program
{
static void Main()
{
Car car = new Car();
car.Start();
car.Drive();
}
}
In this example, the abstract class Vehicle provides a common implementation (Start method) and forces derived classes to implement the Drive method.
What is an Interface in C#?
An interface in C# is a contract that defines what a class must do, but not how it does it. It only contains method signatures, properties, events, or indexers without implementation (except default implementations in newer versions of C#).
Key Features of Interface
Contains only method signatures (by default)
Cannot have constructors
Does not contain fields
Supports multiple inheritance (a class can implement multiple interfaces)
All members are public by default
Example of Interface
interface IVehicle
{
void Start();
void Drive();
}
class Car : IVehicle
{
public void Start()
{
Console.WriteLine("Car is starting...");
}
public void Drive()
{
Console.WriteLine("Car is driving...");
}
}
class Program
{
static void Main()
{
IVehicle car = new Car();
car.Start();
car.Drive();
}
}
Here, the interface IVehicle defines a contract, and the Car class provides the actual implementation.
Join the conversation! Your thoughts help the community grow.