Thursday, June 28, 2012

Virtual Keyword In C#

Virtual Keyword in C#




  • When a derived class want to override  the base class member(s) then base class member(s)  need to marked as virtual members.

  • A function marked as virtual can be overridden by subclasses wishing to provide a specialized implementation.

  • Methods, properties, indexers, and events can all be declared as virtual.

  • In the derived class those members will be marked by override  keyword.



 Following example will illustrates briefly the concept of virtual keyword.


Creating Types


public class Asset


{


public string Name;


public virtual decimal Liability


{


get


{


return 0;


 }


}


}


 A subclass overrides a virtual method by applying the override modifier:


public class Stock : Asset


{


public long SharesOwned;


}


public class House : Asset


{


public decimal Mortgage;


public override decimal Liability


{


get


{


return Mortgage;


}


 }


}


 By default, the Liability of an Asset is 0. A Stock does not need to specialize this behavior. However, the House specializes the Liability property to return the value of the Mortgage:


             House mansion = new House { Name="McMansion",Mortgage=250000 };


              Console.WriteLine (mansion.Liability); // 250000




  •  The signatures, return types, and accessibility of the virtual and overridden methods must be identical.

  • An overridden method can call its base class implementation via the base keyword.