Abstract Class, Methods and Members with example in C#

Abstract Class

Abstract class means, We cannot create the object of this class or no object of this class can be instantiated. We can derive its sub classes which can be instantiated. An abstract class can contain either abstract or non-abstract members. Abstract class , marked by the keyword abstract.

Declaration of abstract class:

  1. abstract class DemoAbstract
  2. {  
  3.   
  4. }  

Abstract Method :

An abstract method does not have any implement in abstract class. It has to be providing in its derived class and marked by the keyword abstract.

  1. abstract class DemoAbstract
  2. {  
  3.   
  4.    public abstract void addTowNumber();  
  5.   
  6.    public int AddThreeNumber(int a, int b, int c)
  7.    {  
  8.   
  9.       return a + b + c;  
  10.   
  11.    }  
  12.   
  13. }  

Note : An abstract calss does not mean that is should contain abstract member We can have an abstract class only with non-abstract member.

  1. abstract class DemoAbstract
  2. {  
  3.     
  4.    public int AddThreeNumber(int a, int b, int c)
  5.    {  
  6.   
  7.       return a + b + c;  
  8.   
  9.    }  
  10.   
  11. }  

Example

  1. abstract class DemoAbstract
  2. {  
  3.   
  4.    /// abstract Properties  
  5.   
  6.    protected String _Myname;  
  7.   
  8.    public abstract String Myname
  9.    {  
  10.   
  11.       get;  
  12.   
  13.       set;  
  14.   
  15.    }  
  16.    /// abstract Methods    
  17.   
  18.    public abstract void addTowNumber(int a, int b);  
  19.   
  20.    public int AddThreeNumber(int a, int b, int c)
  21.    {  
  22.   
  23.       return a + b + c;  
  24.   
  25.    }  
  26.   
  27. }  
  28.   
  29. class DemoDerived : DemoAbstract
  30. {  
  31.   
  32.    // implementing abstract method  
  33.   
  34.    public override void addTowNumber(int a, int b)
  35.    {  
  36.   
  37.       Console.WriteLine(a + b);  
  38.   
  39.    }  
  40.   
  41.    // implementing abstract Member  
  42.   
  43.    public override String Myname
  44.    {  
  45.   
  46.       get
  47.       {  
  48.   
  49.          return _Myname;  
  50.   
  51.       }  
  52.   
  53.       set
  54.       {  
  55.   
  56.          _Myname = value;  
  57.   
  58.       }  
  59.   
  60.    }  
  61.   
  62. }  

Note

  1. An abstract method and properties cannot be static.
  2. An abstract method and properties cannot be private.
  3. An abstract class cannot be sealed calss.
  4. An abstract method and properties cannot have modifier virtual.