#754 – Downcast to a Reference to a Derived Class
January 9, 2013 Leave a comment
If you have a variable that is a reference to a parent class, but it actually refers to an instance of a derived class, you can use a downcast operation to assign the reference to a variable whose type matches the derived class.
For example, assume that you have a Dog class and a Terrier class, which inherits from Dog. You might have a reference to a Dog that actually refers to an instance of a Terrier. To get at methods that are unique to Terrier, you’d downcast the Dog reference to a Terrier reference.
This type of conversion is known as a reference conversion.
// Dog reference that points to a Terrier Dog d = new Terrier("Jack", Terrier.GrowlFactor.Severe); // Can't invoke Terrier methods via Dog reference //d.DoTerrierDance(); // ERROR // Downcast to Terrier. Need explicit conversion Terrier t = (Terrier)d; // Can now treat like Terrier t.DoTerrierDance();