Posts Tagged Visual Basic

Visual Basic’s Explicit Conversion Functions

When learning Visual Basic, I learned many things when working with different data types to perform calculations, and one of them was Visual Basic’s explicit conversion functions. For example, I would use these functions to apply a cast, which there are currently sixteen functions in the .NET 3.5 framework. For example, let’s say I have a Windows Form set up that have two textboxes, and I need to convert both of them to an integer so that I can perform some arithmetic operations on them. A conversion must take place, because all data from a textbox has a string data type.

vb example

Looking at the example above, you can see the explicit conversions that are taking place, but also how I’m using these conversions in my arithmetic calculation. There is one problem with this example, it poses a threat of crashing, because there is a very good chance that the user may enter a value or get a calculation that exceeds the integer’s data type type range, which is –2,147,483,648 to 2,147,483,647. This would require method overloading, but I will save this topic for my next blog entry.

I only used one out of sixteen examples, but each explicit conversion works in a similar way, but I would like to discuss the “CType” function. The “CType” function works a little different, but it is one that you will find yourself using a lot. For example:

lngTest = CType(intVal1, Long)

The example above uses the “CType” function to convert the “intVal1” variable into a long data type. Basically, you put the variable you want to convert on the left side of the comma, and you put the data type you want to convert it to on the right side of the comma. If you are new to programming, you will very soon learn the importance of applying cast, regardless of what programming language you are using.

, , , , , , , , , ,

Leave a comment