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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With