locked
Base Class: ... hides inherited member ... Use the new keyword if hiding was intended. RRS feed

  • Question

  • Hello,

    I have the following base class:

    public class Flag {
      public List<String> Parse() {
      }
    }

    And I have about 8 classes deriving from it ...

    Most classes use the base Parse method but there is one which needs to do extra work:

    public class SizeFlag : Flag {
      public List<String> Parse() {
        return base.Parse().With(x => new List<String> { x[0] }.Union(x[1].Split('x')).ToList());
      }
    }

    I get the following warning:

    Warning    2    'UnitTestProject1.SizeFlag.Parse()' hides inherited member 'UnitTestProject1.Flag.Parse()'. Use the new keyword if hiding was intended.

    Should I add new as "new public List<String> Parse()" in SizeFlag?

    Or should I use virtual in Flag and override in SizeFlag?

    But that does not mean I would need to do in all classes deriving from Flag class?

    What should I do?

    Thank You,

    Miguel

    Friday, March 15, 2013 4:59 PM

Answers

  • The method should be `virtual` in the base class if you want child classes to be able to override it.  The warning you're getting is indicating that, because the base class is not virtual, you cannot override it, you can only shadow it.  By applying the `new` modifier you aren't changing any behavior, you're just indicating more clearly to the reader that the method is shadowing, not overriding, the base class.  Since you don't want to shadow it, you want to override it, you need to modify the base class to make the method virtual.  The warning can't specify that as the solution though, as in many cases the user won't have the ability to change the base class definition.
    • Marked as answer by MDMoura Friday, March 15, 2013 5:17 PM
    Friday, March 15, 2013 5:16 PM

All replies

  • The method should be `virtual` in the base class if you want child classes to be able to override it.  The warning you're getting is indicating that, because the base class is not virtual, you cannot override it, you can only shadow it.  By applying the `new` modifier you aren't changing any behavior, you're just indicating more clearly to the reader that the method is shadowing, not overriding, the base class.  Since you don't want to shadow it, you want to override it, you need to modify the base class to make the method virtual.  The warning can't specify that as the solution though, as in many cases the user won't have the ability to change the base class definition.
    • Marked as answer by MDMoura Friday, March 15, 2013 5:17 PM
    Friday, March 15, 2013 5:16 PM
  • Got it ...

    Thank you for the explanation,

    Miguel

    Friday, March 15, 2013 5:17 PM