Sobes.tech
Junior — Middle

In which cases is it recommended to use abstract classes in object design?

sobes.tech AI

Answer from AI

Abstract classes in C# are recommended to be used when you need to define common base functionality for a group of related classes, but it is either not possible or not necessary to create instances of the base class itself.

Main use cases:

  • When there are common methods and properties that should be present in all derived classes, but some methods need to be implemented in specific classes (abstract methods).
  • For partial implementation of an interface to avoid code duplication in derived classes.
  • When you need to provide a behavior template, leaving implementation details to subclasses.

Example:

public abstract class Animal
{
    public void Eat() {
        Console.WriteLine("Eating food");
    }

    public abstract void MakeSound();
}

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

Here, Animal cannot be instantiated directly, but you can use the common method Eat and require subclasses to implement MakeSound.

In which cases is it recommended to use abstract… - sobes.tech