The first type of conversion that we will discuss is widening conversions. Widening conversions can always hold the value assigned because it is wider/larger than the source. For example: byte->short->integer->long->decimal->single->double.
Here are some examples:
Dim grade as Double = 143 ' (this converts the integer to a Double)
Remember that the Double data type can hold both whole and fractional numbers. Since the variable grade was a whole number of 143, Visual Basic automatically converted it to an integer data type on the fly. Some people call this implicit casting, others may call it implicit conversion. The keyword implicit, means this happens automatically within Visual Basic without the need for any code from you.
Dim a As Double = 6.5
Dim b As Integer = 6
Dim c As Integer = 10
Dim average as Double = (a + b + c) / 3 (converts b and c to Doubles, average = 7.5 (22.5/3)
Narrowing conversions are just the opposite of widening conversions. When this happens a casting exception is thrown and this can cause trouble. VB also does narrowing conversions implicitly--so be careful. You could lose decimal places or reduce numbers by strange values.
Dim grade as Integer = 93.75 (grade equals 93 because the .75 is truncated)
Dim average As Integer = (a + b + c) / 3 (equals 7 because the .5 is truncated)
You can override implicit narrowing casts by coding explicit casts. This doesn't stop exceptions, just controls to a larger degree what type of conversion is to be performed.
To change the type semantics from permissive to strict you can do this per project or for every new project (better idea).
If you want to change this permanently then inside Visual Studio go to Tools, Options and select Compile and make the change.
Keep in mind that the two data types need to be compatible. For example you can not add a number to a string value, this does not make sense.
The key point to take away is that the converted data type must be able to hold the imported data type. In other words it is okay to go from a smaller type to larger, but you get into trouble when trying to take a larger or incompatible type to another.
For example you could convert a Char type to a String or Object, but not any type of numeric data type such as Integer, Double, etc.
You can read up more on this in the online documentation when you have time. For now, just be aware of the concept and as you get more experience you will pull your hair out when a calculation is not resulting as expected or you are getting a compile error that is driving you nuts. Then you will remember this lesson.
In Lesson 5 we will go fire up Visual Studio and build the wage calculation application from the ground up.
Tim