Explicit type conversion basically means “I know what I am doing, so let me covert this into this, because I know it will work”. It is used whenever there is a possibility of data loss. For instance, when converting from ANY real number type into an integer, there is ALWAYS a loss of data, because integers cannot store fractional parts. But if you are sure you really don’t need that fractional part, the explicit cast will work just fine.
Also, as pointed out in a previous article, when converting from a wider range type to a lower range one, there is the possibility of data loss, because the wider range can store a bigger number than the lower one.
The way of explicit converting is to place the type into which you want to convert into parenthesis in front of the value to be converted, like this:
1 2 3 4 |
double myDouble = 2.3d; long myLong = (long)myDouble; //explicitly converts a double to a long int myInt = (int)myDouble; //explicitly converts a double to an int |
Obviously, in our example, our double can be converted into an int, because we know that 2.3 is small enough to fit into an int, and we know that the fractional part will be lost. However,
1 2 |
myDouble = 7e9d; // 7 * 10^9 int myInt = (int)myDouble; |
The above example will fail miserably, because the maximum value of an int is 2147483647, while our double stores 7000000000. We will not get any error or exception, but the value will be incorrect, because of the overflow exception. If we want to make sure such thing does not happen, C# offers us a keyword, checked, which includes checking for an overflow situation in integer types:
1 2 |
myDouble = 7e9d; // 7 * 10^9 int myInt = checked((int)myDouble); //will generate a System.OverflowException error |
The following types can be explicitly converted one to another (remember, with possibility of data loss!):
sbyte, byte, short, ushort, char, int, uint, long, ulong, float, double, decimal
As a final note, you should know that typecasting from and to string from/to other types is not allowed. We will explain conversion from and to string in the next lesson.
The concepts explained in this lesson are also shown visually as part of the following video: