GOTCHA 45 Compilers lean toward hiding virtual methods


GOTCHA #45 Compilers lean toward hiding virtual methods

Programmers coming from C++ are used to marking methods as virtual in a derived class when overriding virtual methods of the base class. However, this habit should not be carried over to .NET. Let's see what happens if you mark a method in the derived class virtual/overridable when a virtual/overridable method with the same name and signature exists in the base class. Consider Example 6-7.

Example 6-7. Another accidental hiding

C# (VirtualInDerived)

 //Base.cs using System; namespace DerivedMethod {     public class Base     {         public virtual void Method1()         {             Console.WriteLine("Base.Method1 called");         }     } } //Derived.cs using System; namespace DerivedMethod {     public class Derived : Base     {         public virtual void Method1()         {             Console.WriteLine("Derived.Method1 called");         }     } } //Test.cs using System; namespace DerivedMethod {     public class Test     {         [STAThread]         static void Main(string[] args)         {             Derived d = new Derived();     Base b = d;     d.Method1();     b.Method1();         }     } } 

VB.NET (VirtualInDerived)

 'Base.vb Public Class Base     Public Overridable Sub Method1()         Console.WriteLine("Base.Method1 called")     End Sub End Class 'Derived.vb Public Class Derived     Inherits Base     Public Overridable Sub Method1()         Console.WriteLine("Derived.Method1 called")     End Sub End Class 'Test.vb Public Class Test     Shared Sub Main()         Dim d As New Derived         Dim b As Base = d         d.Method1()         b.Method1()     End Sub End Class 

Once again, as in Gotcha #44, "Compilers are lenient toward forgotten override/overrides," there is no compilation error. You only get a hidden warning message from the C# compiler:

     warning CS0114: 'DerivedMethod.Derived.Method1()' hides inherited member  'DerivedMethod.Base.Method1()'. To make the current member override that implementation,  add the override keyword. Otherwise add the new keyword.

A similar message appears in the VB.NET version as well. The output from the program is shown in Figure 6-6.

Figure 6-6. Output from Example 6-7


IN A NUTSHELL

Do not mark a method as virtual/overridable if your intent is to override a base method. Mark it as override/overrides.

SEE ALSO

Gotcha #42, "Runtime Type Identification can hurt extensibility," Gotcha #43, "Using new/shadows causes "hideous hiding"," Gotcha #44, "Compilers are lenient toward forgotten override/overrides," Gotcha #46, "Exception handling can break polymorphism," and Gotcha #47, "Signature mismatches can lead to method hiding."



    .NET Gotachas
    .NET Gotachas
    ISBN: N/A
    EAN: N/A
    Year: 2005
    Pages: 126

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net