shows a virtual method called StepUp that is overridden in a derived class with the override modifier
public class CountClass
{
public int count;
public CountClass(int startValue) // constructor
{
count = startValue;
}
public virtual int StepUp()
{
return ++count;
}
}
class Count100Class : CountClass
{
public Count100Class(int x) : base(x) // constructor
{
}
public override int StepUp()
{
return ((base.count) + 100);
}
}
class TestCounters
{
static void Main()
{
CountClass counter1 = new CountClass(1);
CountClass counter100 = new Count100Class(1);
System.Console.WriteLine("Count in base class = {0}", counter1.StepUp());
System.Console.WriteLine("Count in derived class = {0}", counter100.StepUp());
}
}
When you run this code, you see that the derived class's constructor uses the method body given in the base class, letting you initialize the count member without duplicating that code. Here is the output:
Count in base class = 2
Count in derived class = 101