0
0
CsharpConceptBeginner · 3 min read

What is Abstract Class in C#: Definition and Usage

An abstract class in C# is a class that cannot be instantiated directly and is designed to be a base class for other classes. It can contain abstract methods without implementation that derived classes must override, helping to define a common template.
⚙️

How It Works

Think of an abstract class as a blueprint for other classes. You cannot create an object from it directly, just like you cannot build a house from a blueprint alone. Instead, you use it to define common features and rules that other classes must follow.

In C#, an abstract class can have both methods with code (concrete methods) and methods without code (abstract methods). The abstract methods act like empty promises that derived classes must fulfill by providing their own specific behavior. This helps keep your code organized and consistent.

💻

Example

This example shows an abstract class Animal with an abstract method MakeSound. The derived classes Dog and Cat provide their own versions of this method.

csharp
using System;

abstract class Animal
{
    public abstract void MakeSound();

    public void Sleep()
    {
        Console.WriteLine("Sleeping...");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}

class Program
{
    static void Main()
    {
        Animal dog = new Dog();
        dog.MakeSound();
        dog.Sleep();

        Animal cat = new Cat();
        cat.MakeSound();
        cat.Sleep();
    }
}
Output
Woof! Sleeping... Meow! Sleeping...
🎯

When to Use

Use an abstract class when you want to create a common base for related classes that share some behavior but also have their own specific details. It is useful when you want to enforce certain methods to be implemented by all subclasses.

For example, in a game, you might have an abstract class Character with abstract methods like Attack and Defend. Different character types like Warrior and Mage will implement these methods differently.

Key Points

  • An abstract class cannot be instantiated directly.
  • It can contain both abstract methods (without body) and concrete methods (with body).
  • Derived classes must override all abstract methods.
  • It helps define a common interface and shared code for related classes.

Key Takeaways

An abstract class defines a common template but cannot create objects itself.
Abstract methods in the class must be implemented by subclasses.
Use abstract classes to share code and enforce method implementation across related classes.
They help organize code and improve maintainability by defining clear contracts.