Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

small misunderstanding of example in msdn related to virtual/override

Tags:

c#

overriding

While reading about polymorphism in MSDN, I saw an example of virtual and overridden methods:

public class BaseClass
{
    public virtual void DoWork() { }
    public virtual int WorkProperty
    {
        get { return 0; }
    }
}
public class DerivedClass : BaseClass
{
    public override void DoWork() { }
    public override int WorkProperty
    {
        get { return 0; }
    }
}

DerivedClass B = new DerivedClass();
B.DoWork();  // Calls the new method.

BaseClass A = (BaseClass)B;
A.DoWork();  // Also calls the new method.

What I want to know is, in what scenario should someone do this? I just can't see how it is useful in any way. Could someone please give a real-world example?

like image 892
LordTitiKaka Avatar asked Mar 18 '23 12:03

LordTitiKaka


1 Answers

This is useful whenever you want a reference to some objects, and you can't keep references of their exact type. If you for example have a list of objects that are of mixed types:

List<BaseClass> list = new List<BaseClass>() {
  new BaseClass(),
  new DerivedClass(),
  new BaseClass(),
  new BaseClass(),
  new DerivedClass(),
  new DerivedClass()
};

Now you have a list of BaseClass references, but some of them point to DerivedClass instances.

When you want to use them, you don't need to check their type. You can just call the virtual DoWork method, and the BaseClass.DoWork method will be called for the BaseClass instanced and the DerivedClass.DoWork method will be called for the DerivedClass instances:

foreach (BaseClass b in list) {
  b.DoWork();
}
like image 193
Guffa Avatar answered Apr 25 '23 17:04

Guffa