Saturday, May 21, 2022 18:00

Table of contents >> Introduction > Explicit type conversion

Explicit type conversion

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:

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,

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:

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:

Tags: , ,

Leave a Reply

Follow the white rabbit