Some times it is required to convert data from one base data type to another base data type. The Convert Class converts a base data type to another base data type. Convert class throw a FormatException when the attempt was made to convert a String to other base data type and String value is in not proper format. To Handle FormatException we can use Convert class convert method inside try catch block but there is another better way of doing the same thing is to use TryParse to avoide runtime errors and eliminate the need of Try Catch block.
TryParse method is available for all .Net base data type including Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime and String. There are two overloaded versions of TryParse method is available for each .Net base data type.
Boolean.Try Parse
Converts specified String value to equivalent Boolean Value. Return True if Conversion is successful otherwise return False.
Byte.TryParse
Converts Specified String value to equivalent Byte Value. Return True if conversion is successful otherwise return False.
TryParse works in the same way for other base type also.
- Dim Result As Boolean
- Dim ByteResult As Byte
- Dim BooleanResult As Boolean
- Dim IntegerResult As Integer
- Dim DoubleResult As Double
- Dim InputString As String = "1"
- Result = Byte.TryParse(InputString, ByteResult)
- If Result = False Then
- Console.WriteLine(InputString & " is not converted into Byte" & vbCrLf)
- Else
- Console.WriteLine(InputString & " is converted to Byte : " & ByteResult & vbCrLf)
- End If
- InputString = "True"
- Result = Boolean.TryParse(InputString, BooleanResult)
- If Result = False Then
- Console.WriteLine(InputString & " is not converted to Boolean : " & vbCrLf)
- Else
- Console.WriteLine(InputString & " is converted to Boolean : " & BooleanResult & vbCrLf)
- End If
- InputString = "12345"
- Result = Integer.TryParse(InputString, IntegerResult)
- If Result = False Then
- Console.WriteLine(InputString & " is not converted to Integer" & vbCrLf)
- Else
- Console.WriteLine(InputString & " is converted to Integer : " & IntegerResult & vbCrLf)
- End If
- InputString = "12345.111"
- Result = Double.TryParse(InputString, DoubleResult)
- If Result = False Then
- Console.WriteLine(InputString & " is not converted to Double : " & vbCrLf)
- Else
- Console.WriteLine(InputString & " is converted to Double : " & DoubleResult & vbCrLf)
- End If
Leave a comment