Role: You are a senior C#/.NET educator and language-lawyer who writes definitive, citation-backed docs. Your job is to produce the most complete single-source guide on “Abstract Classes – Defining base types with abstract members to implement in subclasses” in C#.
(Use all requirements, structure, and checklist from the Master Prompt.)
Emphases (must cover deeply):
Definition of abstract classes and abstract members; how abstract differs from virtual, override, sealed override, and new hiding.
Rules for instantiation, constructors (including protected/internal), and object initialization with abstract bases.
Interaction with interfaces, default interface members, and explicit interface implementation.
Abstract members and access modifiers, generic constraints, ref/in/out parameters, async, nullable annotations.
Versioning & API design: when to start with abstract base vs. interface; evolving abstract types; binary/source compatibility.
Performance & runtime: virtual dispatch, devirtualization, JIT inlining limits; effect of sealed on overrides in derived non-abstract classes.
Common patterns: Template Method, abstract factories, skeletal implementations (à la Collection patterns).
Pitfalls: forgetting override, accidental new hiding, constructor order, calling virtual members from constructors.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Abstract vs. Virtual vs. Override vs. Sealed Override vs. New Hiding
Instantiation Rules and Object Initialization
Constructors in Abstract Classes
Interaction with Interfaces
Abstract Classes vs. Interfaces
Default Interface Methods
Explicit Interface Implementation
Abstract Members: Advanced Topics
Access Modifiers
Generic Constraints
Ref/In/Out Parameters
Async Abstract Methods
Nullable Annotations
Versioning & API Design Considerations
When to Use an Abstract Class vs. Interface
Evolving Abstract Types
Binary and Source Compatibility
Runtime and Performance
Virtual Dispatch
Devirtualization and JIT Inlining
Effect of Sealed on Overrides
Common Design Patterns
Template Method Pattern
Abstract Factories
Skeletal Implementations (e.g., Collection<T>)
Common Pitfalls
Forgetting to Override
Accidental new Hiding
Constructor Order
Calling Virtual Members in Constructors
Conclusion
References & Further Reading
1. Introduction
Abstract classes are a foundational construct in object-oriented design within C#. They enable the definition of base types with abstract members—methods, properties, or events that must be implemented by derived classes. This guide explores abstract classes in depth, focusing on their usage, constraints, design implications, and performance characteristics.
2. Abstract Classes and Abstract Members
What is an Abstract Class?
An abstract class is a class that cannot be instantiated directly. It may contain abstract members (i.e., methods or properties with no implementation), and may also provide default implementations for some members.
csharp
public abstract class Animal
{
public abstract void MakeSound();
}
Any class inheriting from Animal must implement MakeSound().
ECMA-334 C# Language Specification (Section 17.2.3): “An abstract class is a class that cannot be instantiated directly, and is frequently used to define a common base class for a family of derived classes.”
Abstract vs. Virtual vs. Override vs. Sealed Override vs. New Hiding
Keyword
Meaning
Can Be Overridden?
Must Be Implemented?
abstract
Declares a member with no implementation; must be overridden.
❌ (in abstract class)
✅
virtual
Provides a default implementation; can be overridden.
✅
❌
override
Provides a new implementation in a derived class.
✅ (if not sealed)
❌
sealed override
Overrides a virtual member and prevents further overriding.
❌
❌
new
Hides the base implementation; does not override.
❌
❌
Example:
csharp
public abstract class Base
{
public abstract void A();
public virtual void B() { Console.WriteLine("Base.B"); }
}
public class Derived : Base
{
public override void A() { Console.WriteLine("Derived.A"); }
public override void B() { Console.WriteLine("Derived.B"); }
}
Important Note: Using new instead of override may cause subtle bugs due to member hiding. Use override unless you explicitly want to hide the base implementation.
3. Instantiation Rules and Object Initialization
Abstract Classes Cannot Be Instantiated Directly
Attempting to instantiate an abstract class results in a compile-time error:
csharp
Animal a = new Animal(); // Compile error
Only non-abstract derived classes can be instantiated.
Constructors in Abstract Classes
Abstract classes can have constructors, including:
protected (common for base class logic)
internal (for framework or library usage)
Even public, though rarely useful
Constructors are called when a derived class is instantiated.
Example:
csharp
public abstract class Base
{
protected Base()
{
Console.WriteLine("Base constructor");
}
}
public class Derived : Base
{
public Derived() // Base constructor is implicitly called
{
Console.WriteLine("Derived constructor");
}
}
Output:
code
Base constructor
Derived constructor
ECMA-334 §17.2.3: "Abstract classes may include constructors, which are invoked when instances of derived non-abstract classes are created."
4. Interaction with Interfaces
Abstract Classes vs. Interfaces
Feature
Abstract Class
Interface
Multiple inheritance
❌
✅ (since C# 8.0)
Default implementation
✅
✅ (with default interface methods)
Access modifiers
✅
❌ (except private, internal, etc.)
State (fields)
✅
❌ (C# 8.0+ allows static fields)
Instance constructors
✅
❌
Use abstract classes when you need:
Shared implementation
Access modifiers
State (fields)
Versioned base classes
Use interfaces when you need:
Multiple inheritance
Default implementation (C# 8+)
API contracts with minimal coupling
Default Interface Methods
C# 8.0 introduced default interface methods, allowing interfaces to provide method bodies.
This enables evolution of interfaces without breaking existing implementations.
Abstract Class vs. Default Interface:
Prefer abstract classes when you need state or protected members. Use interfaces with default methods when designing loosely coupled APIs.
Explicit Interface Implementation
Abstract classes can explicitly implement interfaces, just like regular classes.
csharp
public abstract class Base : ILogger
{
void ILogger.Log(string message)
{
Console.WriteLine(message);
}
}
This allows hiding interface methods from derived classes unless explicitly cast.
5. Abstract Members: Advanced Topics
Access Modifiers on Abstract Members
Abstract members can have the following access modifiers:
public (most common)
protected
internal
protected internal
Example:
csharp
public abstract class Base
{
protected abstract void InternalMethod(); // Accessible only to derived types
}
ECMA-334 §17.5.6: "Abstract methods may have any accessibility, including private, though private abstract methods are only useful in nested classes."
Generic Constraints with Abstract Classes
Abstract classes can be used as generic type constraints using where T : BaseClass.
csharp
public abstract class Animal { }
public class Cage<T> where T : Animal
{
public T Resident { get; set; }
}
This ensures T is a subclass of Animal.
Ref/In/Out Parameters in Abstract Methods
Abstract methods can use ref, in, out parameters like any other method.
csharp
public abstract class Base
{
public abstract void Process(ref int value);
}
Implementing classes must match the parameter modifiers exactly.
Async Abstract Methods
You can define async abstract methods:
csharp
public abstract class Base
{
public abstract Task DoAsync();
}
Derived classes must implement them with async Task.
Note: Avoid calling async methods from constructors (see Pitfalls).
Nullable Annotations in Abstract Members
Abstract methods can use nullable reference types:
csharp
public abstract class Base
{
public abstract string? GetName();
}
Derived classes must respect the nullability contract.
6. Versioning & API Design Considerations
When to Use an Abstract Class vs. Interface
Use abstract classes when:
You need shared implementation logic
You need to define protected or internal members
You want to control instantiation (e.g., via protected constructor)
You need state (fields)
Use interfaces when:
You need multiple inheritance
You're defining contracts, not implementations
You expect third-party extensions
Evolving Abstract Types
Adding a new abstract member to an existing abstract class will break all derived classes unless they are updated. This is a source-breaking change.
Recommendation:
Prefer interfaces with default methods when evolving APIs. Alternatively, create a new derived abstract class.
Binary and Source Compatibility
Changing an abstract class can affect both source and binary compatibility:
Adding a new abstract method → breaks existing derived classes (source incompatible)
Adding a virtual method with default implementation → source compatible
Changing access modifiers → may break derived classes (source incompatible)
Use versioning strategies such as:
Introduce new abstract class in next major version
Provide default implementation in new virtual method
7. Runtime and Performance
Virtual Dispatch
Abstract methods are implicitly virtual and participate in virtual method dispatch.
Example:
csharp
Animal a = new Dog();
a.MakeSound(); // Virtual dispatch
This involves a vtable lookup, which is efficient but not inlinable in most cases.
Devirtualization and JIT Inlining
The JIT compiler may devirtualize calls if it can prove the exact runtime type:
csharp
Dog dog = new Dog();
dog.MakeSound(); // May be inlined
However, calls through base class references typically cannot be inlined.
Tip: Use sealed to help the JIT optimizer.
Effect of Sealed on Overrides
Sealing an override prevents further overriding:
csharp
public class Derived : Base
{
public sealed override void A()
{
// ...
}
}
This can improve performance and clarity, as the JIT can devirtualize sealed methods more easily.
8. Common Design Patterns
Template Method Pattern
The template method pattern defines the skeleton of an algorithm in an abstract class, deferring some steps to subclasses.
An abstract factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.
csharp
public abstract class WidgetFactory
{
public abstract Button CreateButton();
public abstract TextBox CreateTextBox();
}
Use Case:
UI frameworks, cross-platform libraries, plugin systems.
Skeletal Implementations (e.g., Collection<T>)
Also known as the partial implementation pattern, abstract classes can provide common functionality, allowing subclasses to implement only the core logic.
csharp
public abstract class Collection<T>
{
protected abstract int Count { get; }
protected abstract T GetItem(int index);
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return GetItem(i);
}
}
Example in .NET: System.Collections.ObjectModel.Collection<T> is a skeletal implementation.
9. Common Pitfalls
Forgetting to Override
If a derived class fails to implement an abstract member, it must also be marked abstract.
csharp
public class Derived : Animal { } // Error: Does not implement MakeSound()
Fix:
csharp
public abstract class Derived : Animal { } // Still abstract
Accidental new Hiding
Using new instead of override hides the base implementation without overriding it.
csharp
public class Derived : Base
{
public new void B() { } // Hides Base.B(), does not override
}
Fix: Use override unless hiding is intentional.
Constructor Order
Base class constructors are always called before derived class constructors.
csharp
public class Base
{
public Base() => Console.WriteLine("Base ctor");
}
public class Derived : Base
{
public Derived() => Console.WriteLine("Derived ctor");
}
Output:
code
Base ctor
Derived ctor
Calling Virtual Members in Constructors
Calling virtual or abstract methods in a constructor can lead to undefined behavior, as the derived class's implementation may not be fully initialized.
csharp
public abstract class Base
{
protected Base() => Initialize();
protected abstract void Initialize();
}
Problem: Initialize() in Base's constructor may call a derived implementation that relies on fields not yet initialized in Derived.
Best Practice:
Avoid calling virtual or abstract methods in constructors.
10. Conclusion
Abstract classes are a powerful tool for defining base types with abstract members and shared implementation logic. They provide a middle ground between full implementation and interface-based contracts.
They are ideal for:
Framework design
Template methods
Skeletal implementations
Controlled inheritance hierarchies
Use them wisely to avoid common pitfalls like:
Accidental member hiding
Constructor order issues
Virtual method calls in constructors
For evolving APIs, consider interfaces with default methods as a more flexible alternative, especially when multiple inheritance or loose coupling is needed.