Tuesday, 9 April 2013

C# New Modifier: How to hide a base class method in derived class?

C# New Modifier: How to hide a base class method in derived class?

The new modifier specifies that a method is supposed to hide a base method. It eliminates a warning issued by the compiler. No functionality is changed. But an annoying warning is silenced.

Example of New Modifier

This program introduces two classes, A and B. The B class derives from the A class. Class A has a public method Y, while class B has a public method Y that uses the new keyword to hide the base method Y.

using System;
class A
{
    public void Y()
    {
       Console.WriteLine("A.Y");
    }
}

class B : A
{
    public new void Y()
    {
       // This method HIDES A.Y.
       // It is only called through the B type reference.
       Console.WriteLine("B.Y");
    }
}

class Program
{
    static void Main()
    {
      A ref1 = new A();
      A ref2 = new B();
      B ref3 = new B();
      ref1.Y();
      ref2.Y();
      ref3.Y();
    }
}

Output
A.Y
A.Y
B.Y

Explanation:

In this example, we use the A and B types. With ref1, the base class is used directly. This results in the A.Y method being used. With ref2, the base class is used with a derived class. This results in the A.Y method being used again. For ref2, the A.Y method is used because the override keyword is not used on B.Y. With ref3, the derived class is used directly. The "new" method B.Y is thus used.

No comments:

Post a Comment