How To Use An Abstract Method In C#

Introduction

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 a requirement that the child class must implement a method? To achieve this, we can declare a 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. Usually, 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 the implementation of an abstract method.

using System;
namespace OOPSProject
{
    abstract class AbsParent
    {
        public void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
        public abstract void Mul(int x, int y); // Only method declaration
        public abstract void Div(int x, int y); // Only method declaration
    }
}
using System;
namespace OOPSProject
{
    class AbsChild : AbsParent
    {
        // First, we have to implement abstract methods of the parent class
        public override void Mul(int x, int y)
        {
            Console.WriteLine(x * y);
        }
        public override void Div(int x, int y)
        {
            Console.WriteLine(x / y);
        }

        static void Main()
        {
            AbsChild c = new AbsChild();
            AbsParent p = c;
            p.Add(100, 50);
            p.Sub(156, 78); // Then we can invoke other methods
            p.Mul(50, 30);
            p.Div(625, 25);
            Console.ReadLine();
        }
    }
}


Similar Articles