Information Technology Reference
In-Depth Information
Case 2—Declaring Print with new
If you declare the
Print
method of
SecondDerived
as
new
, the result is as shown in Figure 7-10.
Main
is the same as in the previous case.
class SecondDerived : MyDerivedClass {
new public void Print() {
↑
Console.WriteLine("This is the second derived class.");
}
}
class Program {
static void Main() // Main
{
SecondDerived derived = new SecondDerived(); // Use SecondDerived.
MyBaseClass mybc = (MyBaseClass)derived; // Use MyBaseClass.
derived.Print();
mybc.Print();
}
}
The result is that when method
Print
is called through the reference to
SecondDerived
, the
method in
SecondDerived
is executed, as you would expect. When the method is called through
a reference to
MyBaseClass
, however, the method call is passed up only one level, to class
MyDerived
, where it is executed. The only difference between the two cases is whether the
method in
SecondDerived
is declared with modifier
override
or modifier
new
.
This code produces the following output:
This is the second derived class.
This is the derived class.
Figure 7-10.
Hiding the overridden methods