#335 – Accessing a Derived Class Using a Base Class Variable
May 31, 2011 2 Comments
You can use a variable whose type is a base class to reference instances of a derived class.
However, using the variable whose type is the base class, you can use it to access only members of the base class and not members of the derived class.
In the example below, we have two instances of the Terrier class, which derives from Dog. One instance is referenced by a variable of type Terrier. Using this variable, you have access to all members of the Terrier class. On the other hand, the variable whose type is Dog can only reference members of the Dog class, even though the reference points to an instance of a Terrier.
Terrier bubba = new Terrier("Bubba", 2, "Happy"); bubba.Growl(); // Can call Terrier.Growl Dog jack = new Terrier("Jack", 17, "Surly"); jack.Growl(); // ERROR: Can't call Growl method
Pingback: #344 – Hidden Base Class Member Is Invoked Based on Declared Type of Object « 2,000 Things You Should Know About C#
Pingback: #356 – Hidden Base Class Property Is Used Based on Declared Type of Object « 2,000 Things You Should Know About C#