Your Ad Here

Friday, August 14, 2009

Data Type Conversion in .Net

Converting between Data types
In Visual Basic, data can be converted in two ways: implicitly, which means the conversion is performed automatically, and explicitly, which means you must perform the conversion.
Implict Conversions
Let's understand implicit conversions in code.
The example below declares two variable, one of type double and the other integer. The double data type is assigned a value and is converted to integer type. When you run the code the result displayed is an integer value, in this case the value displayed is 132 instead of 132.31223.
Imports System.Console
Module Module1
Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=d
WriteLine("Integer value is" & i)
End Sub
End Module
Explicit Conversions
When types cannot be implicitly converted you should convert them explicitly. This conversion is also called as cast.
Explicit conversions are accomplished using CType function.
CType function for conversion
If we are not sure of the name of a particular conversion function then we can use the CType function.



The above example with a CType function looks like this:
Imports System.Console

Module Module1

Sub Main()

Dim d As Double

d = 132.31223

Dim i As Integer

i = CType(d, i)'two arguments, type we are converting from, to type desired

WriteLine("Integer value is" & i)

End Sub

End Module


Below is the list of conversion functions which we can use in VB .NET.
CBool - use this function to convert to Bool data type

CByte - use this function to convert to Byte data type

CChar - use this function to convert to Char data type

CDate - use this function to convert to Date type

CDbl - use this function to convert to Double data type

CDec - use this function to convert to Decimal data type

CInt - use this function to convert to Integer data type

CLng - use this function to convert to Long data type

CObj - use this function to convert to Object type

CShort - use this function to convert to Short data type

CSng - use this function to convert to Single data type

CString - use this function to convert to String data type

No comments:

Post a Comment

Your Ad Here