Using the new Keyword to Reuse Identifiers

You can use the new keyword to redefine an identifier used in a base class. Suppose you are working with an interface that defines a property called ID:

interface BaseInterface {

Now suppose that you'd like to derive from that interface, but you'd like to use the ID identifier as the name of a method:

interface DerivedInterface : BaseInterface {

This construct causes the C# compiler to issue a warning relating to the reuse of the identifier ID:

warning CS0108: The keyword new is required on 'DerivedInterface.ID()' because it hides inherited member 'BaseInterface.ID'

The compiler is warning that the identifier ID is used twice: once in the base interface as a property identifier, and once in the derived interface as a method name. This name reuse will most likely be confusing to users of the interface. The compiler warning means that the use of the ID keyword in the derived interface takes precedence over the use of the ID keyword in the base interface. If a piece of code obtains an implementation of the DerivedInterface interface, the code is unable to call the ID() method but cannot access the ID property in the base interface. The reuse of the ID identifier in the derived interface hides the ID identifier in the base class, and clients cannot access the base interface's property.

To work around this issue, you can use the keyword new when the identifier is reused. This use of the new keyword, shown in the following example, tells the C# compiler that you intend to provide a new usage for the reused symbol:

interface DerivedInterface : BaseInterface {

0 0

Post a comment