C# Abstraction

Abstraction means hiding complex details and showing only what is necessary. In C#, abstract classes and abstract methods let you define a template that other classes must follow.

What Is Abstraction?

Data abstraction is the idea of hiding certain details and only showing the important parts to the user. When you drive a car you press the pedal to go faster; you do not need to know how the engine works inside. C# gives you two main tools for abstraction: abstract classes and interfaces. This page focuses on abstract classes.

Abstract Classes and Methods

An abstract class is a restricted class that cannot be used to create objects directly. To use it, you must inherit from it in another class. An abstract method is a method that has no body inside the abstract class. Any class that inherits the abstract class must provide the body by overriding the method.

Declaring an abstract class

abstract class Animal
{
    // abstract method: no body here
    public abstract void MakeSound();

    // a normal method is still allowed
    public void Sleep()
    {
        Console.WriteLine("Zzz...");
    }
}

class Pig : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The pig says: oink oink");
    }
}
Note: You cannot write new Animal() because Animal is abstract. You must create an object of a class that inherits from it, such as new Pig().
  • An abstract class can have both abstract methods and normal methods.
  • An abstract method has no body and must be overridden by the child class.
  • You cannot create an object from an abstract class directly.
  • Abstract members can only appear inside an abstract class.

Why Use Abstraction?

Abstraction lets you define a shared shape for a group of related classes while forcing each class to fill in its own specific behaviour. This gives you security, because the internal details are hidden, and consistency, because every derived class is guaranteed to provide the required methods.

Using the abstract class

class Program
{
    static void Main()
    {
        Pig myPig = new Pig();
        myPig.MakeSound();  // The pig says: oink oink
        myPig.Sleep();       // Zzz...
    }
}
FeatureAbstract Class
Create objects directlyNo
Can have normal methodsYes
Can have abstract methodsYes
Must be inherited to useYes

Exercise: C# Abstraction

In C#, what does marking a class with the `abstract` keyword prevent?