C# Abstract Methods
In C#, an abstract method is a method that has no implementation. It is declared in an abstract class and it must be implemented by any non-abstract derived class. An abstract method is marked with the abstract
keyword, and it can only be used in an abstract class.
Syntax
The syntax for declaring an abstract method is as follows:
1abstract void MethodName();
An abstract method cannot have any implementation. It must be implemented by any non-abstract derived class.
Example
Here is an example of an abstract method in C#:
1abstract class Shape 2{ 3 public abstract void Draw(); 4} 5 6class Circle : Shape 7{ 8 public override void Draw() 9 { 10 Console.WriteLine("Drawing Circle"); 11 } 12} 13 14class Rectangle : Shape 15{ 16 public override void Draw() 17 { 18 Console.WriteLine("Drawing Rectangle"); 19 } 20} 21 22class Program 23{ 24 static void Main(string[] args) 25 { 26 Shape circle = new Circle(); 27 Shape rectangle = new Rectangle(); 28 29 circle.Draw(); // Output: Drawing Circle 30 rectangle.Draw(); // Output: Drawing Rectangle 31 } 32}
In the above example, we have defined an abstract class Shape
, which has an abstract method Draw()
. The Draw()
method has no implementation in the Shape
class, but it is implemented in the derived classes Circle
and Rectangle
.
Benefits of Abstract Methods
Abstract methods provide a way to define a common interface for a set of classes. This allows for polymorphism, which allows the code to work with objects of different classes through a common interface. In the above example, the Draw()
method provides a common interface for the Circle
and Rectangle
classes, allowing the Main
method to work with both classes through the Shape
interface. This makes the code more modular and easier to maintain.