CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
Understanding Custom Type Conversions
Let’s now examine a topic closely related to operator overloading: custom type conversions. To set the
stage for the discussion, let’s quickly review the notion of explicit and implicit conversions between
numerical data and related class types.
Recall: Numerical Conversions
In terms of the intrinsic numerical types (sbyte, int, float, etc.), an explicit conversion is required when
you attempt to store a larger value in a smaller container, as this could result in a loss of data. Basically,
this is your way to tell the compiler, “Leave me alone, I know what I am trying to do.” Conversely, an
implicit conversion happens automatically when you attempt to place a smaller type in a destination
type that will not result in a loss of data:
static void Main()
{
int a = 123;
long b = a;
int c = (int) b;
}
// Implicit conversion from int to long.
// Explicit conversion from long to int.
Recall: Conversions Among Related Class Types
As shown in Chapter 6, class types may be related by classical inheritance (the “is-a” relationship). In
this case, the C# conversion process allows you to cast up and down the class hierarchy. For example, a
derived class can always be implicitly cast to a base type. However, if you want to store a base class type
in a derived variable, you must perform an explicit cast, like so:
// Two related class types.
class Base{}
class Derived : Base{}
class Program
{
static void Main(string[] args)
{
// Implicit cast between derived to base.
Base myBaseType;
myBaseType = new Derived();
}
}
// Must explicitly cast to store base reference
// in derived type.
Derived myD erivedType = (Derived)myBaseType;
This explicit cast works due to the fact that the Base and Derived classes are related by classical
inheritance. However, what if you have two class types in different hierarchies with no common parent
(other than System.Object) that require conversions? Given that they are not related by classical
inheritance, typical casting operations offer no help.
412