C# Abstract Classes
Learn C# through interactive, bite-sized lessons. Build .NET applications with hands-on practice.
Start C# Journey →Abstract classes are a fundamental concept in C# and object-oriented programming. They serve as a blueprint for other classes, providing a common structure and behavior while allowing for specialized implementations.
What are Abstract Classes?
An abstract class is a special type of class that cannot be instantiated directly. It's designed to be inherited by other classes, known as concrete classes. Abstract classes can contain both abstract and non-abstract members.
Key Features of Abstract Classes
- Cannot be instantiated
- May contain abstract and non-abstract methods
- Can have constructors and destructors
- Can implement C# Interfaces
Syntax and Usage
To declare an abstract class in C#, use the abstract keyword before the class definition. Here's a basic example:
public abstract class Shape
{
public abstract double CalculateArea();
public void Display()
{
Console.WriteLine($"Area: {CalculateArea()}");
}
}
In this example, Shape is an abstract class with an abstract method CalculateArea() and a concrete method Display().
Implementing Abstract Classes
To use an abstract class, you must create a derived class that implements all abstract members. Here's an example:
public class Circle : Shape
{
private double radius;
public Circle(double r)
{
radius = r;
}
public override double CalculateArea()
{
return Math.PI * radius * radius;
}
}
The Circle class inherits from Shape and provides an implementation for the abstract CalculateArea() method.
When to Use Abstract Classes
Abstract classes are useful in several scenarios:
- When you want to provide a common interface for a group of related classes
- To define a base class that encapsulates common functionality
- When you need to declare non-public members or methods
Abstract Classes vs. Interfaces
While abstract classes and C# Interfaces serve similar purposes, they have key differences:
| Abstract Classes | Interfaces |
|---|---|
| Can have implementation details | Only method signatures (prior to C# 8.0) |
| Support single inheritance | Support multiple inheritance |
| Can have constructors | Cannot have constructors |
Best Practices
- Use abstract classes to define a common base for a family of related classes
- Implement abstract methods in derived classes using the
overridekeyword - Consider using interfaces for multiple inheritance scenarios
- Avoid creating deep inheritance hierarchies
Abstract classes play a crucial role in C# Inheritance and Polymorphism. They provide a powerful way to design flexible and extensible class hierarchies in your C# applications.