Thursday, April 9, 2009

virtual keyword in C#

If a base class method is to be overriden, it is defined using the keyword virtual
The class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful.

When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following example will be helpful to understand.

public class Shape
{
string name;
public virtual void SetName(string name)
{ this.name = name; }
}


public class Circle : Shape
{
//This method is being overriden
public override void SetName(string name)
{
base.SetName("circle"); //We are calling parent class method
}
}

No comments: