Hiding Methods from the Base ClassWhen you derive one class from another the derived class inherits all the non-private members of the base class. The derived class can then declare methods specific to the derived class to extend the base class. But what happens if the author of the base class adds a method with the same name as a method in the derived class? And what happens if the base class and the derived class have members that have the same name? The answer is that C# by default uses a mechanism called hide-by-signature. Hide-by-signature means that the compiler will try to combine all the methods from the base class and the derived class as long as the methods don't conflict in some way. Two methods would conflict if they had the exact same name and parameters. Another source of conflict would be if one of the members of the class were a field and the derived class had a method with the same name. This would be a conflict because you can't have a method and field with the same name. When there is a conflict, the compiler will choose what version of the method to use depending on how you declare the variable to use the class. If the variable is of the type of the base class, then only the base class method can be invoked. If the variable is of type of the derived class, then only the derived version of the function can be invoked. Even though this is the default behavior, the compiler issues a warning that hiding is occurringwhich leads us to the steps of this topic. To suppress the warning resulting from hiding:
Tips
Figure 5.23 When a method in the derived class is identical to a method in the base class the compiler warns you that method hiding is taking place. You can tell the compiler that you meant to do that by adding the new keyword in front of the function's return type.class Account { protected decimal m_balance = 0.0m; // default implementation of // MakeDeposit public void MakeDeposit (decimal amount) { m_balance +=amount; } } class Checking : Account { // specialized Checking implementation // of MakeDeposit public new void MakeDeposit (decimal amount) { if (amount > 500.0m) m_balance +=amount; else // do some validation first if (ValidateDeposit()) m_balance +=amount; else throw new InvalidOperationException(); } public bool ValidateDeposit() { // include some validation on the // deposit return true; } } |