Use the new keyword if hiding was intended(CS0108)

If you are using the inheritance in c# and are wanting to override (hide) the base class method but forget to use the ‘new’ keyword then you will get the warning.

Use the new keyword if hiding was intended(CS0108)

An example of this in coding syntax would be something like

class BC 
{
  public void DisplayMe()
  {
    System.Console.WriteLine("Display me from BC");
  }
}
// inherited class from BC
class NewBC : BC 
{
  public void DisplayMe()
  {
    System.Console.WriteLine("Display me from the NewBC :) yeppy");
  }
}
 
NewBC NBC = new NewBC();
NBC.DisplayMe();

and the output would be

Display me from the NewBC :) yeppy

If you note that the base class in the NBC has not been called from the NBC.DisplayMe() method e.g. “Display Me from BC”

But you will get the warning message from the compiler

Use the new keyword if hiding was intended(CS0108)

So all you do is to put the keyword ‘new’ before the overriding method e.g.

// inherited class from BC
class NewBC : BC 
{
  new public void DisplayMe()
  {
    System.Console.WriteLine("Display me from the NewBC :) yeppy");
  }
}

2 thoughts on “Use the new keyword if hiding was intended(CS0108)”

  1. you seem to have copy and paste error, that interestingly will execute as intended but defeats the purpose of this article
    class NewBC : BC
    should be
    class new BC : BC

  2. I am enraged by this warning – it seems pointless – why not just make it an error not to use the new keyword?

    As it stands it seems we have two syntactii for doing the exact same thing, but with one you get a capricious warning that you should never be using that form

Leave a Reply

Your email address will not be published.