Abstract Class in C# Explained

Abstract class provides a common definition of a base class that many derived classes can share.

The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.

Tips:

  • An abstract class cannot be instantiated.
  • Derived classes of the abstract class must implement all abstract methods

 

Abstract class can be declared in C# using the keyword abstract as shown in the example below:

public abstract class MyAbstractClass
{
    // Class members go here.
}

Abstract classes can have abstract methods and can be defined in C# using the keyword abstract as shown below:

public abstract class MyAbstractClass
{
    public abstract void MyAbstractMethod(int i);
}

Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block as shown below.

public abstract class MyAbstractClass
{
    public abstract void MyAbstractMethodButNoImplementation(int i);
}

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method, as shown in following example:

public class D
{
    public virtual void BaseVirtualMethod(int i)
    {
        // Original implementation here.
    }
}

public abstract class E : D
{
    public abstract override void BaseVirtualMethod (int i);
}

public class F : E
{
    public override void BaseVirtualMethod (int i)
    {
        // New implementation here.
    }
}

 

Reference:

MSDN

Tags: