Casting Within Inheritance Hierarchies
Learn about type casting in C#, including implicit and explicit casting.
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.