I am having problems understanding dynamic polymorphism in C#, which led me to another problem which is creating instances.
What I know :
- Dynamic polymorphism is method overriding.
- Inheritance must occur(in other words we must have a base and derived class)
I have the following code:
// Base Class
public class BClass
{
public virtual void GetInfo()
{
Console.WriteLine("Learn C# Tutorial");
}
}
// Derived Class
public class DClass : BClass
{
public override void GetInfo()
{
Console.WriteLine("Welcome to the tutorial");
}
}
class Program
{
static void Main(string[] args)
{
DClass d = new DClass();
d.GetInfo();
BClass b = new BClass();
b.GetInfo();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
I have two classes: BClass(Parent Class)/DClass(Child Class that derives from BClass) What happened here is that the method GetInfo()(in BClass) was overridden inside DClass. And for the overriding to work we had to add two keywords: virtual(in the base class), overridden(in derived class). What if I remove these 2 keywords, so public void GetInfo()[base class]/public void GetInfo()[derived class]. My output will be the same. I will still have
- Learn C# Tutorial
- Welcome to the tutorial
As if the concept of overriding never happened before removing the keywords.
Now I tried to search online, and found out that for overriding to take effects the creation of instances inside Main() must be different.
- ** BClass d = new DClass();[Instead DClass d = new DClass()]**
- ** BClass b = new BClass();**
But why would anyone use BClass d = new DClass() instead of DClass d = new DClass(), when all we want to do is create an instance of the DClass.
So to summarize everything:
- I don't understand polymorphism, because when I removed the keywords the output did not change
- I don't know how to properly create instances, because in some examples I see: DerivedClass x = new DerivedClass(), in other examples BaseClass x = new DerivedClass() which is totally confusing.