Connecting Tech Pros Worldwide Forums | Help | Site Map

C# new and override

Newbie
 
Join Date: Feb 2008
Posts: 8
#1: Sep 16 '08
I am pretty new to C# (and anything really other than web languages). I am trying to understand two keywords in C# dealing with polymorphism. Can you please tell me if the following is correct?

New keyword – just states that there is a method in the child class with the same name as one in the base class, prevents an error. Hides the child method from the parent method.
Override keyword - Child method that actually overrides the method of the same name in the parent class.

If the new keyword as I stated is correct, why would you ever even create a method with the same name within a child class. Wouldn't it always be over-written by the parent?

Expert
 
Join Date: Sep 2008
Location: USA
Posts: 188
#2: Sep 16 '08

re: C# new and override


"the new keyword explicitly hides a member inherited from a base class. Hiding an inherited member means that the derived version of the member replaces the base-class version." (C# Lang Ref)

"Hides the child method from the parent method" is probably not precise.

The child method replaces the parent method entirely. The inheritance chain is stopped. In a certain sense, the parent method is now "hidden" to you child class.

A contrived example based on something I came across once is setting a static value (note: this is not good design, just an example):
Expand|Select|Wrap|Line Numbers
  1. public abstract class CheckingAccount{
  2.   public static int StartValue = 250;
  3. }
  4.  
All my derived classes would share that StartValue. If I change it in one class:

Expand|Select|Wrap|Line Numbers
  1. public class DadsCheckingAccount : CheckingAccount{
  2.   public DadsCheckingAccount(){
  3.     StartValue = -1;
  4.   }
  5. }
  6.  
it is now changed for all my classes.

However, if for one derived class I declare
Expand|Select|Wrap|Line Numbers
  1. public class DadsCheckingAccount : CheckingAccount{
  2.   new public static int StartValue = 500;
  3. }
  4.  
it is now changed just for DadsCheckingAccount without affecting other CheckingAccount derived classes.
Reply