2.4 Type Conversion
In the previous topic, we looked at data types in C#, but in programming often the values of one type of variable are assigned to the variables of another type. There are two types of conversion that we are going to consider now.
When data of one type is assigned to a variable of another type, implicit type conversion occurs automatically under the following conditions:
- both types are compatible;
- the target type’s range of numbers is wider than that of the source type;
All implicit conversions can be described by the following list (type comes first, then types to which you can casting implicitly):
- byte — short, ushort, int, uint, long, ulong, float, double, decimal;
- byte — short, int, long, float, double, decimal;
- sbyte — short, int, long, float, double, decimal;
- short — int, long, float, double, decimal;
- ushort — int, uint, long, ulong, float, double, decimal;
- int — long, float, double, decimal;
- uint — long, ulong, float, double, decimal;
- long — float, double, decimal;
- ulong — float, double, decimal;
- float — double;
- char — ushort, int, uint, long, ulong, float, double, decimal;
There is an implicit conversion here, because the range of int values is greater than that of short, thus the compiler will implicitly expand each variable of type short to type int and no data is lost. But if we do the opposite, we get an error, because short has less range of values and size in memory.
int — 4 bytes, range — -2147483648 to 2147483647;
short — 1 bytes, range — -32768 to 32767;
This is where explicit conversion can help.
As useful as implicit type conversions are, they fail to meet all programming needs as they allow only extensible conversions of compatible types (see table above). In all other cases, you have to use explicit type casting.
The essence of the type casting operation is that before the value, the type to which the given value must be cast is indicated in brackets.
In the example below we explicitly casting a variable of type int to type byte:
Let’s look at another example:
Why does the num2 have a value 44? Because the number 300 does not fall within the valid range for the byte type (0, 255) and invalid numbers will be truncated.
How to solve this issue? We can choose another data type instead of byte, for example, short. But there are situations when we do not know exactly what value a num1 will have. To avoid such situations, C# has the checked keyword.
When using the checked keyword, the application throws an overflow exception. We will talk about exception and the try/catch block later, just be aware that the checked keyword is used inside try/catch.
Previous article -> 2.3 Data Types
Next article -> 2.5 Console Input/Output
Join to our community in Telegram — https://t.me/itifico
If you want to support me, you can buy me a cup of coffee and I will drink it when I write the next article :)
- Dinesh Chintalapudi — 3$
- Unknown — 5$
- Neisy — 3$