I can hide an inherited member without the new operator so when why utilize it to do so?

From what I have tested in code it seems like there is no point in using the new operator to hide an inherited member. So why even utilize the new operator to do so?

public class Test
{
    public static void Main(string[] args)
    {
        Bar temp = new Bar();

        temp.GetMessage(); 
    }
}

public class Foo
{
    public void GetMessage()
    {
        Console.WriteLine("Message Foo");
    }
}

public class Bar : Foo
{
    public void GetMessage()
    {
        Console.WriteLine("Message Bar");
    }
}

//output: Message Bar

>Solution :

Lets visit the documentation

When used as a declaration modifier, the new keyword explicitly hides
a member that is inherited from a base class. When you hide an
inherited member, the derived version of the member replaces the base
class version. This assumes that the base class version of the member
is visible, as it would already be hidden if it were marked as
private or, in some cases, internal. Although you can hide public or
protected members without using the new modifier, you get a compiler
warning
. If you use new to explicitly hide a member, it suppresses
this warning.

The warning is to primarily warn you what you are about to do, and the new modifier is to explicitly show you (and your team mates, and the poor coders who come after you) what you have reasoned about and considered. Ignore it at your own peril and the ire of anyone who maintains your code

Its worth noting, using the new modifier like this is generally fairly suspect, and could point to a design problem. It is a lot more common to override the member instead of replacing it, and much less likely to cause hard to debug runtime errors in production.

Leave a Reply