What is an abstract class in C#?

Classes can be defined as user-defined data types representing an object’s state (properties) and behavior (actions).

Types of classes

There are four types of classes in C#, which are as follows:

  1. Abstract Class
  2. Partial Class
  3. Sealed Class
  4. Static Class
Types of classes in C#
Types of classes in C#

In this Answer, we’ll only discuss the abstract class.

Abstract class

An abstract class is defined as a class that is declared using the abstract keyword and whose object is not created. This type of class provides a standard definition for the subclasses.

To access the object of this class, it must be inherited from another class.

Example

If we run the following code, it will generate an error as we cannot generate an object of the class of type abstract.

abstract class Car
{
public abstract void startengine();
public void enginesound()
{
System.Console.WriteLine("Broom!");
}
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
}
}

Explanation

In the code above:

  • Line 1: We generate a class car of type abstract. The class type is declared using a specific keyword, abstract.
  • Lines 2–8: These are the methods specific to the class Car.
  • Line 9: This class Program contains the main program that executes and generates an error signifying that we cannot create an object of the class car.

We can solve the problem by making a derived class. Try executing the following code. It will not generate any error.

abstract class Car
{
public abstract void startengine();
public void enginesound()
{
System.Console.WriteLine("Broom!");
}
}
class BMW : Car
{
public override void startengine()
{
System.Console.WriteLine("Engine started.");
}
}
class Program
{
static void Main(string[] args)
{
BMW myBMW = new BMW();
myBMW.startengine();
myBMW.enginesound();
}
}

Note: The code above uses C# version 7 or later.

The code above is the same as the previous one, but lines 9–15 contain a derived class BMW. In lines 20–22, we generate an object of class BMW rather than that of car. Therefore, there is no error in the execution of the code.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved