Option Strict

 

o   When working with different data types it is important NOT to mix them.  While assigning one data type to another does not ALWAYS cause problems it CAN cause problems

 

Dim intNumber As Integer

Dim sngNumber As Single

 

sngNumber = 4.3

intNumber = sngNumber

 

Label1.Text = intNumber

 

Results in the value 4.3 to be rounded.

 

But

Dim intNumber As Integer

Dim sngNumber As Single

 

sngNumber = 12345678657534

intNumber = sngNumber

 

Label1.Text = intNumber

Causes a run time error

 

 

 

 

To be notified of these potential errors before we execute the program we can set

 

Option Strict ON

 

In the General Declaration section of your code

 

With Option Strict ON the IDE will not allow you to mix data types or declare variable without a data type clause

 

 

 

 

When assigning a value that is a “smaller” data type to a “larger” data type variable (like assigning an integer to a long) VB will automatically do an implicit conversion. But in order to do the opposite (a long to an integer) or to store input from a TextBox (a string value) in a numeric variable you must do an explicit conversion. The Visual Basic 2010 supports a class named Convert that contains methods that we can use to perform explicit type conversion.

 

Convert.ToInt16(value) Converts to Short data type
Convert.ToInt32(value) Converts to Integer data type
Convert.ToInt64(value) Converts to Long data type
Convert.ToDecimal(value)  
Convert.ToSingle(value)  
Convert.ToDouble(value)  
Convert.ToString(value)  

 

 

        For example

 

        decNumber = 1234

        intNumber = Convert.ToInt16(decNumber)

 

Since the Text property is treated as a String data type you must use the Convert Class to convert the numerals entered in Text property to a numeric value stored in a numeric variable. 

 

                        decPrincipal = Convert.ToDecimal(txtPrincipal.Text)

 

 

 

And when you display a value in a numeric variable in a label you must convert it to a string. This can be easily done because every numeric data type has a built in method – ToString – to convert the numeric value to a string.

 

 

 

 

 

Even when you do explicitly cast variables it does not guarantee there won’t be any problems when the program is executed.

 

 

 

 

In the future we will learn how to write your code to catch problems before they result in “unhandled exceptions”.