[C# Howto] How to Cast Non-related Types?

Casting types between primitive types is very intuitive and easy to understand. Casting between class types are based on the inheritance hierarchy. Cating the derived to the base can be implicit. But casting the base to derived should be done explicitly.

How about casting one type to another that is not hierarchically related?

1. Cast non-related types

Let’s look at the following 2 classes: Point2D and Point3D

public class Point2D
{
  public int X { get; set; }
  public int Y { get; set; }
}

public class Point3D
{
  public int X { get; set; }
  public int Y { get; set; }
  public int Z { get; set; }
}

Two classes are not related from their definitions. So casting any one type to another will fail. Now the new requirement is that all Point2D objects should be recreated to Point3D objects. You can provide a conversion method but your manager thinks simple casting is simpler and cleaner.

In most cases, this kind of cast does not make much sense and makes code hard to read. But if you really want to do it or needs to do it, it is lucky for you that C# provides the construct to define the conversion rules.

2.Casting Syntax

The syntax is pretty easy beause it uses the same syntax of the operator overloading.

public static [explicit | implicit] operator TypeTo(TypeFrom t)
{
  return new TypeTo(...);
}

If you specify the “explict” keyword, only the explicit conversion is allowed. If the “implicit” is specified, both explicit and implicit conversion are allowed.

3. Overloading the cast operator

Let’s implement the logic to convert Point2D to Point3D in the Point3D class.

public class Point3D
{
  public static explicit operator Point3D(Point2D p)
  {
    return new Point3D { X = p.X, Y = p.Y, Z = 0 };
  }
}

Point2D p = new Point2D { X = 1, Y = 2 }; Point3D p1 = (Point3D)p;
Console.WriteLine("X={0}, Y={1}, Z={2}", p1.X, p1.Y, p1.Z);

Only the explicit conversion will work. If you want to allow implicit conversion too, just change the “explicit” to “implcit“.

public static implcit operator Point3D(Point2D p)
{
  return new Point3D { X = p.X, Y = p.Y, Z = 0 };
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s