How to Create Abstract Class in C#: Syntax and Example
In C#, create an abstract class using the
abstract keyword before the class keyword. Abstract classes cannot be instantiated directly and can contain abstract methods that must be implemented by derived classes.Syntax
An abstract class is declared with the abstract keyword before class. It can have abstract methods without a body, which derived classes must implement. You cannot create objects of an abstract class directly.
- abstract class ClassName: Declares the abstract class.
- abstract returnType MethodName();: Declares an abstract method without implementation.
- Concrete methods can also be included with full implementation.
csharp
public abstract class Animal { public abstract void MakeSound(); public void Sleep() { Console.WriteLine("Sleeping..."); } }
Example
This example shows an abstract class Animal with an abstract method MakeSound. The derived class Dog implements MakeSound. The program creates a Dog object and calls its methods.
csharp
using System; public abstract class Animal { public abstract void MakeSound(); public void Sleep() { Console.WriteLine("Sleeping..."); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Bark!"); } } class Program { static void Main() { Animal myDog = new Dog(); myDog.MakeSound(); myDog.Sleep(); } }
Output
Bark!
Sleeping...
Common Pitfalls
- Trying to create an instance of an abstract class directly causes a compile error.
- Forgetting to implement all abstract methods in derived classes causes a compile error.
- Abstract methods cannot have a body; adding one causes a compile error.
Example of wrong and right usage:
csharp
/* Wrong: Cannot instantiate abstract class */ // Animal animal = new Animal(); // Error /* Wrong: Missing implementation of abstract method */ // public class Cat : Animal { } // Error /* Right: Implement abstract method */ public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow!"); } }
Quick Reference
| Concept | Description |
|---|---|
| abstract class | Defines a class that cannot be instantiated and may contain abstract methods. |
| abstract method | A method declared without implementation; must be overridden in derived classes. |
| override | Keyword used in derived class to provide implementation of an abstract method. |
| Instantiation | You cannot create objects of an abstract class directly. |
| Concrete methods | Abstract classes can have normal methods with full implementation. |
Key Takeaways
Use the abstract keyword before class to create an abstract class in C#.
Abstract classes cannot be instantiated directly; create objects of derived classes instead.
All abstract methods must be implemented in non-abstract derived classes using override.
Abstract methods cannot have a body; only declarations are allowed.
Abstract classes can contain both abstract and concrete methods.