Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Convert One Type to Another

Scenario/Problem:

You need to convert one type to another, either automatically or by requiring an explicit cast.

Solution:

Implement a conversion operator. There are two types of conversion operators: implicit and explicit. To understand the difference, we’ll implement a new struct called Vertex3i that is the same as Vertex3d, except the dimensions are integers instead of doubles.

Explicit Conversion (Loss of Precision)

Explicit conversion is encouraged when the conversion will result in a loss of precision. When you’re converting from System.Double to System.Int32, for example, all of the decimal precision is lost. You don’t (necessarily) want the compiler to allow this conversion automatically, so you make it explicit. This code goes in the Vertex3d class:

public static explicit operator Vertex3i(Vertex3d vertex)
{
    return new Vertex3i((Int32)vertex._x, (Int32)vertex._y, (Int32)vertex._z);
}

To convert from Vertex3d to Vertex3i then, you would do the following:

Vertex3d vd = new Vertex3d(1.5, 2.5, 3.5);
Vertex3i vi = (Vertex3i)vd;

If you tried it without the cast, you would get the following:

//Vertex3i vi = vd;
Error: Cannot implicitly convert type 'Vertex3d' to 'Vertex3i'.
       An explicit conversion exists (are you missing a cast?)

Implicit Conversion (No Loss of Precision)

If there will not be any loss in precision, then the conversion can be implicit, meaning the compiler will allow you to assign the type with no explicit conversion. We can implement this type of conversion in the Vertex3i class because it can convert up to a double with no loss of precision.

public static implicit operator Vertex3d(Vertex3i vertex)
{
    return new Vertex3d(vertex._x, vertex._y, vertex._z);
}

Now we can assign without casting:

Vertex3i vi = new Vertex3i(1, 2, 3);
Vertex3d vd = vi;
  • + Share This
  • 🔖 Save To Your Account