C# Reference ยท Keywords and Statements
The abstract keyword
Reference for the C# abstract keyword: abstract classes, abstract methods and properties, how they differ from virtual members and interfaces.
abstract marks something as incomplete on purpose. An abstract class cannot be instantiated; it exists to be a base for other classes. An abstract member (method, property, indexer or event) has no body: every non-abstract derived class must provide one with override.
Use an abstract class when several related types share state or behavior but the base alone makes no sense, such as Shape with Circle and Square. The base can contain ordinary fields, constructors and complete methods next to the abstract ones, which is the main advantage over an interface.
abstract class Shape { public abstract double Area(); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
[modifiers] abstract class Name { ... } abstract ReturnType Method(params); abstract Type Property { get; set; } abstract event EventHandler Changed; public abstract override string ToString(); // re-abstract an inherited member
Rules:
| Rule | Detail |
|---|---|
| Abstract members | Implicitly virtual; cannot be private, static or sealed; have no body. |
| Where allowed | Only inside an abstract class (or an interface, where all members are abstract implicitly). |
| Derived classes | Must override every inherited abstract member, or be abstract themselves. |
| Constructors | Allowed. They run when a derived object is created, and should be protected or public. |
Errors: new on an abstract type is CS0144; a non-abstract class missing an override is CS0534.
Usage notes
- Abstract versus virtual:
virtualsupplies a default that may be overridden;abstractsupplies nothing and forces an override. - Abstract versus interface: a class has one base class but many interfaces. Choose an abstract class for shared code or fields, an interface for a capability that unrelated types can have.
- A class can be abstract with no abstract members, just to prevent direct instantiation.
- Do not call abstract methods from the base constructor. The derived class's fields are not initialized yet, so the override sees default values.
abstractandsealedconflict: a class cannot be both. Astaticclass cannot be abstract.- Test doubles: abstract members are easy to substitute in tests with a small derived class.
- Overriding in a derived abstract class with
abstract overridemakes subclasses implement it again.