C# 101: Virtual Function Members Vs Abstract Function Members

by silvercrux @ 12. March 2010 12:13

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.





Comments

3/13/2010 2:37:32 AM #

trackback

SilverCrux.com Blog | C# 101: Virtual Function Members Vs Abstract Function Members

Thank you for submitting this cool story - Trackback from DotNetShoutout

DotNetShoutout

3/13/2010 8:20:11 PM #

trackback

SilverCrux.com Blog | C# 101: Virtual Function Members Vs Abstract Function Members

Thank you for submitting this cool story - Trackback from iAwaaz-News-by-People

iAwaaz-News-by-People

3/15/2010 11:37:36 AM #

pingback

Pingback from blog.cwa.me.uk

The Morning Brew - Chris Alcock  » The Morning Brew #559

blog.cwa.me.uk

3/16/2010 12:01:21 PM #

pingback

Pingback from tamm79.de

Markus Tamm  » Blog Archive   » Links 16.03.2010

tamm79.de

5/21/2010 11:24:41 AM #

pingback

Pingback from 135.cmanager.org

Cbr929rr Discount Motorcycle Parts, T929 Pirate Bay

135.cmanager.org

Comments are closed

© Copyright SilverCrux Technologies. All rights reserved. We provide website html services.