Virtual methods are extremely useful but can also be abused.
Imagine a base class that has a method
SetText
public virtual void SetText(string text)
{
this.text = text;
}
public string Text
{
get { return text; }
}
This method may be enough for the base classes purposes, but a derived class may prefer to validate the parameter or raise an event etc.
public event EventHandler TextChanged;
protected virtual void OnTextChanged(EventArgs e)
{
EventHandler eh = TextChanged;
if(eh != null)
eh(this, e);
}
public override void SetText(string text)
{
text = ValidateText(text);
if(Text != text)
{
base.SetText(text);
OnTextChanged(EventArgs.Empty);
}
}
private string ValidateText(string text)
{
string result = null;
return result;
}
You can see how the method has been made a lot more powerful but without changing the overall function of the method.
Note, I have deliberately called
base.SetText
. You should (normally) always call the base classes method when overriding to make sure any other functionality that may be part of that method is retained. Not doing so can lead to unpredictable results and possibly breaking of an application if the base class is later updated.