In VB, you cannot just say, for example, a 'number'. You have to say a particular type of number. Does it have decimals? If not, then an Integer, Short or Long. If it has decimal places, then a Single, Double or Decimal, depending on the accuracy required.
Mostly we don't need to dabble in converting different data types when writing our code, because we choose one that works and stick to it. However, some functions NEED a specific data type, and therefore we need to convert, or cast it, to the correct data type.
Here is a reference list of all the conversion functions in VB.NET. Think of the letter C as standing for 'cast':
- CBool(expression) - Boolean
- CBytel(expression) - Byte
- CChar(expression) - Char
- CDate(expression) - Date
- CDbl(expression) - Double
- CDec(expression) - Decimal
- CInt(expression) - Integer
- CLng(expression) - Long
- CObj(expression) - Object
- CSByte(expression) - SByte
- CShort(expression) - Short
- CSng(expression) - Single
- CStr(expression) - String
- CUint(expression) - UInteger
- CULong(expression) - ULong
- CUShort(expression) - UShort
Each function takes a single parameter - the data to cast - and returns a value of the type to which it is casting to. For example:
[highlight=vb]
Dim dblValue As Double = 35.35
Dim sngValue As Single
sngValue = CSng(dblValue)
'Both variables now contain the same value.
'Value of sngValue == Value of dblValue
[/highlight]
I hope this helps anyone who needs to convert between the data types in VB - casting is very common, especially to strings (using CStr), but remember that every object automatically inherits a ToString() method to convert the value to string, and that the data types have Parse() and TryParse() method in addition, which is very useful is you are using a .NET language other than VB.
Please +rep if helpful. Leave comments here!
Edited by Xav, 29 July 2008 - 10:12 AM.


Sign In
Create Account


Back to top









