Access Method of Parent Class with Instance of Child Class

What is Inheritance?

Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Inheritance makes it easier to create and maintain an application.

How to implement inheritance

First we have to create parent class with some methods in BaseClass.cs

  1. using System;  
  2. namespace OopsTutorial  
  3. {  
  4.     class BaseClass  
  5.     {  
  6.         internal BaseClass()  
  7.         {  
  8.             Console.WriteLine("Baseclass Constructor Executed!!");  
  9.         }  
  10.         internal void Print()  
  11.         {  
  12.             Console.WriteLine("BaseClass Print Method Executed");  
  13.         }  
  14.     }  
  15.     class ChildClass : BaseClass  
  16.     {  
  17.         internal ChildClass()  
  18.         {  
  19.             Console.WriteLine("ChildClass Constructor Executed!!");  
  20.         }  
  21.         internal new void Print()  
  22.         {  
  23.             Console.WriteLine("ChildClass Print Method Executed");  
  24.         }  
  25.     }  
  26. }  
In program.cs
  1. using System;  
  2. namespace OopsTutorial  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             BaseClass bc = new BaseClass();  
  9.             ChildClass cc = new ChildClass();  
  10.             BaseClass bccc = new ChildClass();  
  11.             bc.Print();  
  12.             cc.Print();  
  13.             Console.WriteLine("============");  
  14.             bccc.Print();  
  15.             Console.ReadKey();  
  16.         }  
  17.     }  
  18. }  
Output :

program output

Ebook Download
View all
Learn
View all