C# new and override

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Esmeralda
    New Member
    • Feb 2008
    • 8

    #1

    C# new and override

    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?
  • mldisibio
    Recognized Expert New Member
    • Sep 2008
    • 191

    #2
    "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):
    Code:
    public abstract class CheckingAccount{
      public static int StartValue = 250;
    }
    All my derived classes would share that StartValue. If I change it in one class:

    Code:
    public class DadsCheckingAccount : CheckingAccount{
      public DadsCheckingAccount(){
        StartValue = -1;
      }
    }
    it is now changed for all my classes.

    However, if for one derived class I declare
    Code:
    public class DadsCheckingAccount : CheckingAccount{
      new public static int StartValue = 500;
    }
    it is now changed just for DadsCheckingAcc ount without affecting other CheckingAccount derived classes.

    Comment

    Working...