Search⌘ K
AI Features

Abstract Classes

Explore the use of abstract classes in C# to define shared blueprints for related classes without allowing direct instantiation. Understand how to create constructors, implement abstract members like methods, and enforce design contracts that require derived classes to specify their behavior. This lesson helps you grasp inheritance fundamentals and apply object-oriented programming principles effectively in .NET.

C# includes abstract classes alongside concrete classes. An abstract class is a class that cannot be instantiated. It can hold shared functionality for its derived classes.

Abstract classes are useful when we need to define shared behavior without creating instances of the base concept. They serve as a blueprint, allowing us to share common logic while enforcing a design contract that requires derived classes to handle specific implementation details.

Creating an abstract class

Consider the Vehicle, Car, and Motorcycle classes. The Vehicle class holds members common to all vehicles. A vehicle is an abstract concept, while cars and motorcycles are concrete entities.

We mark the Vehicle class as abstract to prevent it from being instantiated directly.

C# 14.0
namespace AbstractClasses;
// Made our class abstract
public abstract class Vehicle
{
public string? Model { get; internal set; }
public decimal Price { get; internal set; }
public int NumberOfWheels { get; internal set; }
}
  • Line 1: We declare a file-scoped namespace to organize the code.

  • Line 4: We use the abstract keyword to define the class. This prevents the class from being instantiated directly.

  • Line 6: We make Model a nullable string (string?) because it might not be set immediately upon instantiation.

  • Lines 7–8: We define other properties that will be inherited by all derived classes. ...