Casting Within Inheritance Hierarchies
Explore how to safely cast between base and derived classes in C#. Learn implicit and explicit casting methods, and understand how to use is and as keywords to avoid exceptions when working within inheritance hierarchies.
Casting between types is subtly different from converting between types. Casting is between similar types, like between a 16-bit integer and a 32-bit integer or between a superclass and one of its subclasses. Converting is between dissimilar types, such as between text and a number.
For example, if we need to work with multiple types of streams, then instead of declaring specific types of streams, like MemoryStream or FileStream, we could declare an array of Stream, the supertype of MemoryStream and FileStream.
Implicit casting
We saw how an instance of a derived type can be stored in a variable of its base type (or its base’s base type, and so on). When we do this, it is called implicit casting ...