C#: Abstract class

This entry is part 58 of 71 in the series C#

An abstract class in C# is a class without implementation or methods.  As there is no method, you will have to develop the member functions in the derived class.

What is the purpose? You might ask.

The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

In a way, creating abstract class is good for organizing code and versionning.  If new parameters in the abstract class declaration are needed, you can always modify the relevant declaration without breaking the code.

using System;

namespace Abstract
{
    public class Music
    {
        public virtual void Display(int i)
        {
            Console.WriteLine("Original implementation {0}", i);
        }
    }

    public abstract class Rock : Music
    {
        public abstract override void Display(int i);
    }

    public class Metal : Rock
    {

        public override void Display(int i)
        {
            Console.WriteLine("New implementation {0}", i);
        }
    }

    class Program
    {
        static void Main()
        {

            Metal metal = new Metal();
            int i = 10;

            metal.Display(i);
            Console.ReadKey();
        }
    }
}

Notice the Display() method in line 15.  As there is no implementation, the declaration of the abstract method ends with a semicolon without a block of code.

public abstract override void Display();

An abstract class is actually a virtual class and it has to be overridden. Also, you cannot create an instance of an abstract class.

 

 

Series Navigation<< C#: Virtual method
C#: Overriding a built-in method ToString >>