Using Abstract Class In C#

A few important points to  remember about an abstract class are given below.

  • Abstract class cannot be directly instantiated but it can be instantiated through the base class object by type casting to it.
  • Abstract class must contain at least one abstract method, which has no definition.

Now, let us see with the code snippets given below. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. //sandip patil practices  
  7. namespace AbstractclassDemo {  
  8.     class MyProgram {  
  9.         abstract class A {  
  10.             //Here show() is abstract method  
  11.             public abstract void show();  
  12.             public void disp() {  
  13.                 Console.WriteLine("Display My Information");  
  14.             }  
  15.         }  
  16.         class B: A {  
  17.             public override void show() {  
  18.                 Console.WriteLine("show");  
  19.             }  
  20.         }  
  21.         class Test {  
  22.             static void Main(string[] args) {  
  23.                 //A a = new A(); //Not allowed  
  24.                 B b = new B();  
  25.                 A a = (A) b; //Allowed-> here actually you will came  
  26.                 // into know how to initialize abstract class instance  
  27.                 a.disp();  
  28.                 Console.Read();  
  29.             }  
  30.         }  
  31.     }  
  32. }  
  33. }   
Ebook Download
View all
Learn
View all