Casting is the process of converting a value from one data type to another. This is often unnecessary by default in VB.NET, as Option Strict is disabled in the Visual Studio Express IDE. In C# it is enabled, but you should enable this in VB as well, from the Project Properties pages, to ensure you write the best code possible, with no possible loss of data, due to improper casting.
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!


LinkBack URL
About LinkBacks







Reply With Quote





Bookmarks