C# Abstract Class
In C#, an abstract class is a class that cannot be instantiated directly. It is used as a base class for other classes, and can contain both abstract and non-abstract methods. Abstract methods are methods that are declared but do not contain an implementation.
Declaring an Abstract Class
To declare an abstract class in C#, use the abstract
keyword in the class declaration. The class can contain one or more abstract methods, as well as non-abstract methods.
1abstract class Shape 2{ 3 // Abstract method 4 public abstract void Draw(); 5 6 // Non-abstract method 7 public void Resize() 8 { 9 Console.WriteLine("Resizing..."); 10 } 11}
Implementing an Abstract Class
To implement an abstract class in C#, you must create a derived class that inherits from the abstract class. The derived class must provide an implementation for all abstract methods declared in the abstract class.
1class Circle : Shape 2{ 3 public override void Draw() 4 { 5 Console.WriteLine("Drawing a circle"); 6 } 7} 8 9class Rectangle : Shape 10{ 11 public override void Draw() 12 { 13 Console.WriteLine("Drawing a rectangle"); 14 } 15}
Creating an Object from a Derived Class
You cannot create an object directly from an abstract class, but you can create an object from a derived class that implements the abstract class.
1Shape shape1 = new Circle(); 2Shape shape2 = new Rectangle();
Benefits of Abstract Classes
Abstract classes allow you to create a hierarchy of classes that share common functionality. They also provide a level of abstraction, allowing you to create a base class that defines the interface for a set of derived classes. This can help to make your code more modular and easier to maintain.