#356 – Hidden Base Class Property Is Used Based on Declared Type of Object

When you use the new modifier to hide a base class property, its property accessors will still be called by objects whose type is the base class.  Objects whose type is the derived class will use the new property in the derived class.

            Dog kirby = new Dog("Kirby", 15);
            kirby.Temperament = "EAGER";
            Console.WriteLine(kirby.Temperament);  // Kirby is eager

            Terrier jack = new Terrier("Jack", 15);
            jack.Temperament = "CraZY";
            Console.WriteLine(jack.Temperament);  // Terrier Jack is CRAZY

We could also use a variable of type Dog (the base class) to refer to an instance of a Terrier (the derived class).  If we then reference the Temperament property using this base class variable, the Temperament property in the base class is used, even though we’re working with an instance of the derived class.

            Dog kirby = new Dog("Kirby", 15);
            kirby.Temperament = "EAGER";      // Uses Dog.Temperament

            Dog jack = new Terrier("Jack", 15);
            jack.Temperament = "CraZY";       // Also uses Dog.Temperament
Advertisement