This series is going to be a C# refresher that reminds you of C# features you sometimes forget.
A function can be marked as virtual when you don’t want your sub-classes to compulsorily provide implementation of some specialized form. So you can treat virtual as opposite of abstract, where you have to compulsorily provide implementation.
Consider this small fragment :
1: public abstract class Person
2: {3: public abstract string Name {get;}
4: public virtual decimal TotalDebts
5: { 6: get 7: {8: return 0;
9: } 10: } 11: } 12: 13: public class RichPerson : Person
14: {15: public override string Name
16: {17: get {return "I am Rich";}
18: } 19: } 20: 21: public class PoorPerson : Person
22: {23: public override string Name
24: {25: get {return "I am just a Poor guy";}
26: } 27: 28: public override decimal TotalDebts
29: {30: get{return 1000000;}
31: } 32: }In this example the property “Name” declared in Line 3 is abstract while property “TotalDebts” in Line 4 is virtual. The difference is while it is compulsory for deriving class to override “Name”, it is optional for deriving class to override “TotalDebts”. In this particular case PoorPerson is under heavy debt and implements TotalDebts to return his TotalDebts.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.