Wednesday, June 19, 2019 00:56

Casting and type conversion

Casting and type conversion generally refers to modifying a data type into another data type. In order to perform an operation on two data types, we need to convert both to the same data type. Type conversion if of two kinds: implicit and explicit.

There are times when using an operation with two data types will generate an exception. There are other times when the two data types are silently converted to the same type, in behind, operation called hidden type conversion. For instance, when we are concatenating an integer to a string, the .NET runtime converts the int to a string on the fly, without our intervention:

hidden type conversion

Explicit conversion allows us to specifically allow a value of a certain type to be treated as another type during the execution of the program, and sometimes this requires certain validations.

Here are two samples of when explicit conversion requires validation upon transformation, and when does not:

  • when converting from object to string, verification is required, because the program needs to know if the object really is a string and not something else.
  • when converting from string to object, no verification is required, string type derives from object type (we will learn about this in the future)
  • converting from int to real types can be made without verification, because there is no danger of losing data (integer is smaller than real types, and also integer can’t have decimals)
  • when converting from double to long, depending on the values involved, it is possible to get data loss, therefor you need explicit conversion from 64-bit floating point to 64-bit integer.

You should know that types cannot be converted to any type, there are only acceptable values. For instance, if you have an integer of value 1 or 0, you can successfully convert it to a Boolean type, but any other value would generate an error, because Boolean cannot have any other value except for true (1) or false (0).

EXERCISES
1. Declare two variables of type string and give them values “Hello” and “World”. Assign the value obtained by the concatenation of the two variables of type string (do not miss the space in the middle) to a variable of type object. Declare a third variable of type string and initialize it with the value of the variable of type object (you should use
type casting).

Solution

Comments

comments

Tags: , , , ,

Leave a Reply