Sushant Shinde

Sushant Shinde

  • NA
  • 83
  • 1.1k

Understanding Polymorphism, inheritance in C#.

Oct 1 2018 1:33 AM
Hello, I am little confused about polymorphism, inheritance in C#.
 
While learning about polymorphism, I found something like this ParentClass P = new ChildClass(); which is a bit confusing. Why would someone create type of parent class to store the object of child class? However it is valid in c# I just want to understand 3 things:
 
1. What is the purpose of doing this?
 
2. What are the advantages of doing this?
 
3. When we should create object like this?
 
Below is my code for reference:
  1. using System;  
  2. class ParentClass  
  3. {  
  4. public void Display()  
  5. {  
  6. Console.WriteLine("Display method in Parent class");  
  7. }  
  8. }  
  9. class ChildClass : ParentClass  
  10. {  
  11. public void Display()  
  12. {  
  13. Console.WriteLine("Display method in Child class");  
  14. }  
  15. }  
  16. public class Program  
  17. {  
  18. public static void Main()  
  19. {  
  20. ParentClass P = new ChildClass();  
  21. P.Display();  
  22. }  
  23. }  
The output of the code is:
 
Display method in Parent class.
 
Now if someone has to call method in parent class why not simply create
 
ParentClass P = new ParentClass();
 
Or if someone has to call method in Child class why not simply create
 
ChildClass C = new ChildClass();
 
Have gone through lot of forums, still not found the answer I want. Please if anyone can explain in detail. It would be great. Thanks. 

Answers (3)