c# - small misunderstanding of example in msdn related to virtual/override -
while reading about polymorphism in msdn, saw example of virtual , overridden methods:
public class baseclass { public virtual void dowork() { } public virtual int workproperty { { return 0; } } } public class derivedclass : baseclass { public override void dowork() { } public override int workproperty { { return 0; } } } derivedclass b = new derivedclass(); b.dowork(); // calls new method. baseclass = (baseclass)b; a.dowork(); // calls new method.
what want know is, in scenario should this? can't see how useful in way. please give real-world example?
this useful whenever want reference objects, , can't keep references of exact type. if example have list of objects of mixed types:
list<baseclass> list = new list<baseclass>() { new baseclass(), new derivedclass(), new baseclass(), new baseclass(), new derivedclass(), new derivedclass() };
now have list of baseclass
references, of them point derivedclass
instances.
when want use them, don't need check type. can call virtual dowork
method, , baseclass.dowork
method called baseclass
instanced , derivedclass.dowork
method called derivedclass
instances:
foreach (baseclass b in list) { b.dowork(); }
Comments
Post a Comment