Rediscovering C#: method hiding

Method hiding in C# programming language is really interesting feature. If in object-oriented context you want to hide derived method when calling base class method in implementation use “new” keyword. Look close at the following example:

using System;

namespace MethodHiding
{
class BaseClass
{
public void Method() { Console.WriteLine("Called base class method."); }
}

class DerivedClass : BaseClass
{
public new void Method() { Console.WriteLine("Called derived class method."); }
}

class Test
{
static void Main(string[] args)
{
BaseClass B = new BaseClass();
DerivedClass D = new DerivedClass();

B.Method(); // result: "Called base class method."
D.Method(); // result: "Called derived class method."

// what if on base class is implemented derived class and the same method is called?
B = new DerivedClass();
B.Method(); // result: "Called base class method."

Console.ReadLine();
}
}
}

Do you have any following questions about method hiding feature in C#?

Leave a Reply

Your email address will not be published. Required fields are marked *