What is an abstract class?
An abstract class is a class that cannot be instantiated directly and must be inherited by a subclass. Abstract classes are used to provide a common base for a set of related classes and to define a common interface that those classes must implement.
An abstract class can contain both abstract and non-abstract methods and properties. Abstract methods and properties are declared with the abstract
keyword and do not have an implementation. Instead, they must be implemented by any class that inherits from the abstract class.
Common uses case for abstract classes
As we said before abstract classes are classes that cannot be instantiated on their own, but rather serve as blueprints for other classes to inherit from. Here are some common use cases for abstract classes in C#:
Encapsulating common functionality: Abstract classes can provide a common set of methods, properties, and fields that are used across multiple related classes. By encapsulating this common functionality in an abstract class, you can reduce code duplication and make your code more modular and maintainable.
Implementing polymorphism: Abstract classes can be used as base classes for polymorphic behavior. Polymorphism allows you to write code that can work with objects of different classes, as long as those classes implement the same set of methods or properties defined in the abstract class.
Enforcing a contract: Abstract classes can be used to define a contract or interface that other classes must adhere to. By defining a set of methods or properties in an abstract class, you can ensure that any class that inherits from that abstract class must implement those methods or properties.
Providing default implementations: Abstract classes can provide default implementations for methods that are not required to be overridden by inheriting classes. This can be useful when you want to provide a default behavior for a method, but still allow inheriting classes to override that behavior if needed.