6.9.08

Method Hiding in C#.NET

  • Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System;

namespace Polymorphism

{

class A

{

public void Foo()

{ Console.WriteLine("A::Foo()"); }

}

class B : A

{

public new void Foo() { Console.WriteLine("B::Foo()"); }

}

class Test

{

static void Main(string[] args)

{

A a = new A();

B b = new B

a.Foo(); // output --> "A::Foo()"

b.Foo(); // output --> "B::Foo()"

a = new B();

a.Foo(); // output --> "A::Foo()"

}

}

}

Conclusion

  • Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.
  • Know what your doing and look out for compiler warnings.

No comments: