Information Technology Reference
In-Depth Information
The following code is the same as in the previous section, but this time, the methods are
labeled
virtual
and
override
. This produces a result that is very different from that of the pre-
vious example. In this version, calling the method through the base class invokes the method
in the derived class.
class MyBaseClass {
virtual public void Print()
{
Console.WriteLine("This is the base class.");
}
}
class MyDerivedClass : MyBaseClass {
override public void Print()
{
Console.WriteLine("This is the derived class.");
}
}
class Program {
static void Main()
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass)derived;
↑
derived.Print();
Cast to base class
mybc.Print();
}
}
This code produces the following output:
This is the derived class.
This is the derived class.
Other important information about the
virtual
and
override
modifiers is the following:
The overriding and overridden methods must have the same accessibility. In other
words, the overridden method cannot be, for example,
private
, and the overriding
method
public
.
You cannot override a method that is
static
or is non-virtual.
Methods, properties, and indexers (which I covered in the preceding chapter), and
another member type, called
events
(which I will cover later in the text), can all be
declared
virtual
and
override
.