C# Abstract Classes and Methods

Updated on     Kisan Patel

In C#, you can have a single base class and multiple derived classes. If you do not want that any class can create an object of the base class, you can make the base class as abstract.

The abstract keyword in a class indicates that the class cannot be instantiated. So You can only create instance of its derived class (only if it is not marked as abstract).

abstract class BaseClass
{
}

class ChildClass : BaseClass
{
}

class Program
{
    static void Main(string[] args)
    {
        BaseClass bc = new BaseClass(); // Can't instantiated
        ChildClass cc = new ChildClass(); // Can be instantiated
    }
}

In the above example, we cannot instantiated the BaseClass class because we have declared it as abstract. So the compiler will generate an error.

c-sharp-abstraction-example

Note : When you declare a class as abstract class, then it requires at least one abstract method in it.

An abstract method is similar to a virtual method which does not provide any implementation; therefore, an abstract method does not have method body. It can be declared by using the abstract keyword.

For Example,

abstract class BaseClass
{
    public abstract int Sum(int a, int b);
    //Method sum() can't be implemented here...
}

class ChildClass : BaseClass
{
    //Method sum() implemented here
    public override int Sum(int a, int b)
    {
        return a + b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        ChildClass cc = new ChildClass();
        int sum = cc.Sum(10, 30);
        Console.WriteLine("The sum of 10 and 30 is : " + sum);
    }
}

the output of above code…

c-sharp-abstract-method-example


C#

Leave a Reply