Similarly to C++ , C# allow redefinition of inherited methods in the derived classes at the cost of hiding the inherited ones.
Although hiding is not an error, but it does cause the compiler to issue a warning. To suppress this warning you have to include the new modifier in the derived method.
The real benefit of this feature is to be sure that you intentionally want to hide the base method and this did not happen by accident or misspelling.
Conversely, if you declare a method as new and it does not really hide a base method, the compiler will also issue a warning, that can be suppressed by removing the new modifier.
Consider the following example :
public class baseHello{ public void sayHello(){ System.Console.WriteLine("base says hello"); } } class derivedHello:BaseHello{ public void sayHello(){ System.Console.WriteLine("derived says hello"); } }
The preceding code will compile fine but the compiler warns you that method derivedHello.sayHello() hides the method baseHello.sayHello() :
warning CS0114: 'derivedHello.sayHello()' hides inherited member 'baseHello.sayHello()'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
As the warning suggest it is preferable to use new like the following.
class derivedHello:BaseHello{ new public void sayHello(){ System.Console.WriteLine("derived says hello"); } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|