1.4.15 How to Cast Primitive Types

There are times when writing code where you need to do equations or assign something and the types of the 'things' don't match up. This is an issues with type compatibility. To fix this, then, we can use a tool called casting to ensure that the types can interact with each other.

The idea of type compatibility can be exemplified as shapes.

If you have a circle (double) trying to fit into a square (decimal) it isn't going to work.

BUT if you say, "hey circle you're a square now!" you can get the shapes to fit.

The same can be said of code. For example, in the code below, this.Wage is a decimal and this.HoursWorked is a double. With an error message that basically says "You are trying to multiply a circle with a square, but I don't know how to do that."

What we can do then, is cast one of the types as the other type. You can do this by putting the type in parenthesis before the value like this:

We picked to cast the this.HoursWorked field as a decimal because the variable the equation is being assigned to is a decimal.

Note that doing this is different than doing:

This will still throw an error because this.HoursWorked is still a double in the equation.

However, you CAN cast equations as different types if the equation's types are the same. For example, if you wanted to write an equation that for some odd reason calculated fatStacks by using the person's Weight and their HoursWorked it would look like this:

You can see there is an error, though, because Weight and HoursWorked are both doubles but fatStacks is a decimal. To fix this you can cast the whole equation like this: