Abstract Class in C#

Here let us try to understand the concept of Abstract Class. You can also read our other articles on Sealed Classes, Interface.

Abstract Classes are the classes that contain abstract fields – methods / properties(only declaration) or non abstract methods(with defination). They are created with the help of abstract keyword. The abstract methods do not provide any concrete defination but required a derived class to implement its abstract methods.

abstract class X
   {
     public void methodA() 
     { // defination of A(); 
     }
     public  abstract void B(); // only declared
     public  abstract void C(); // only declared
    }
    class Y : X
    {
        void B()
        { //here provide the implementation code 
        }
        void C()
        { // body of C() 
        }
    }




Importance of Abstract Method

It is important in situations where some functionality of the class is invariant, and leave the implementation of other methods for derived classes until a specific implementation is needed.
Realtime Examples : It is the heart of many architectural frameworks like IoC, pipelines, plug-ins etc.

Some points to remember:

  • We can’t create the object of Abstract class.
  • This class is intended only to become a base class (Inheritance)
  • Those methods / properties which are only declared and not implemented should be marked as ‘abstract’
  • The abstract methods must be implemented by the derived class
  • The abstract methods of the base class is implemented with the help of ‘override’ keyword.
  • You cannot use ‘sealed’ modifier with your abstract class as both keywords have opposite meaning. One is meant for Inheritance (abstract) and other does not allow inheritance (sealed)
  • abstract fields can only be used in abstract classes

Note : Interface and Abstract Classes are very closely related to each other.

Abstract

Tip : Abstract methods should me choosen very wisely, not very few nor too much. If they are very few it become useless and if it is too many, it become difficult to implement all of them.

You may like to read
Sealed Class
Interface