-1

I am having problems understanding dynamic polymorphism in C#, which led me to another problem which is creating instances.

What I know :

  1. Dynamic polymorphism is method overriding.
  2. 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.
Anthony Kez
  • 37
  • 1
  • 1
  • 4
  • The difference might make more sense if you think of the object being constructed in one place but used in another. E.g., I have written code that expects a `BClass`, you can pass an instance of `DClass` to that code, even though my code doesn't know anything about `DClass`. – Joe Sewell Sep 28 '20 at 15:02

2 Answers2

1

Output will change if you try to call DClass via BClass variable/reference:

public class BClass
{
    public virtual void GetInfo() => Console.WriteLine("In BClass");
}    
// Derived Class
public class DClass : BClass
{
    public override void GetInfo() => Console.WriteLine("In DClass");
}

BClass d = new DClass();
d.GetInfo();
BClass b = new BClass();
b.GetInfo();

Prints:

In DClass
In BClass

While next:

public class BClass
{
    public void GetInfo() => Console.WriteLine("In BClass");
}    
// Derived Class    
public class DClass : BClass
{
    public void GetInfo() => Console.WriteLine("In DClass");
}

BClass d = new DClass();
d.GetInfo();
BClass b = new BClass();
b.GetInfo();

Prints (and also gives you compiler warning CS0108 which signals about method hiding):

In BClass
In BClass

And for why's - you can have a collection of BClass like List<BClass> where you can put instances of both classes. You can have the same method which can handle both BClass and DClass parameters accepting the parent one, basically both classes having the same contract and possibly sharing parts of implementation. See this question for more info.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

It depends on what you want to achieve.

First off both

DerivedClass x = new DerivedClass();

and

BaseClass x = new DerivedClass()

will do the exact same things - this is both will create an object of DerivedClass. The only difference is the reference to that object: ine the first case it´s of the derived type, in the second one of the base-type.

But why would anyone use BClass d = new DClass() instead of DClass d = new DClass(),

There are pretty many reasons for them, one is changability. Imagine your requirements change at some point - and believe me, they will. If you´d allways use the most derived type you had to modify that type on every new requirement. Afterall your drived class gets bigger and bigger. If you´d use a more abstract base-type, you can easily extend it or even replace it by a completely different type without any existing code to change. See also this question: Why would one create a Base Class object with reference to the Derived Class

Why is the output the same

Maybe you noticed some compiler-warning in your first code - something like

Member GetInfo from DClass hides member GetInfo from BClass. If you intend to hide that, consider using the new keyword.

If you do not use any keyword, new is implictely added to the signature, which effectivly hides the base-implementation. Depending on the type of the reference that points to your instance you will then get either the base-implementaion or the derived one, which could be pretty hard to follow. If you´d use the base-type in the first place and virtual/override, you allways get into the most derived implementation - the override.

As a general rule you should never force clients of your code to rely on a specific type, but instead on some abstraction. In other words: only expect what is absoluetly essential for your own code. If the same can be achieved with a more abstract type, you should consider to expect that instead.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111