How To Use An Abstract Method In C#

We know that when a method is declared as virtual, it can be implemented in a child class but it is optional. But what if there is requirement that child class must implement a method. To achieve this, we can declare method as an abstract method. When a method is declared as an abstract method, it is mandatory for all derived classes to implement it. Otherwise, the compiler will throw an error. Uually the parent class has a body and signature of the method without any implementation. The derived or child class has the actual implementation of the method.
 
If you're new to Abstract classes, read here: Abstract Class In C# 
 
Some important points about abstract methods: 
  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) 
Here is an example of implementation of an abstract method.
  1. using System;  
  2. namespace OOPSProject  
  3. {  
  4. abstract class AbsParent  
  5. {  
  6. public void Add(int x, int y)  
  7. {  
  8. Console.WriteLine(x + y);  
  9. }  
  10. public void Sub(int x, int y)  
  11. {  
  12. Console.WriteLine(x - y);  
  13. }  
  14. public abstract void Mul(int x, int y);//only method declaration  
  15. public abstract void Div(int x, int y);//only method declaration  
  16. }  
  17. }  
  18. using System;  
  19. namespace OOPSProject  
  20. {  
  21. class AbsChild : AbsParent  
  22. {  
  23. //first we have to implement abstract methods of parent class  
  24. public override void Mul(int x, int y)  
  25. {  
  26. Console.WriteLine(x * y);  
  27. }  
  28. public override void Div(int x, int y)  
  29. {  
  30. Console.WriteLine(x / y);  
  31. }  
  32. static void Main()  
  33. {  
  34. AbsChild c = new AbsChild();  
  35. AbsParent p = c;  
  36. p.Add(100, 50); p.Sub(156, 78);//then we can invoke other methods  
  37. p.Mul(50, 30); p.Div(625, 25);  
  38. Console.ReadLine();  
  39. }  
  40. }  
  41. }