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.

Code Snippet
  1. Dim Result As Boolean
  2.         Dim ByteResult As Byte
  3.         Dim BooleanResult As Boolean
  4.         Dim IntegerResult As Integer
  5.         Dim DoubleResult As Double
  6.         Dim InputString As String = "1"
  7.  
  8.         Result = Byte.TryParse(InputString, ByteResult)
  9.         If Result = False Then
  10.             Console.WriteLine(InputString & " is not converted into Byte" & vbCrLf)
  11.         Else
  12.             Console.WriteLine(InputString & " is converted to Byte : " & ByteResult & vbCrLf)
  13.         End If
  14.  
  15.         InputString = "True"
  16.         Result = Boolean.TryParse(InputString, BooleanResult)
  17.         If Result = False Then
  18.             Console.WriteLine(InputString & " is not converted to Boolean : " & vbCrLf)
  19.         Else
  20.             Console.WriteLine(InputString & " is converted to Boolean : " & BooleanResult & vbCrLf)
  21.         End If
  22.  
  23.         InputString = "12345"
  24.         Result = Integer.TryParse(InputString, IntegerResult)
  25.         If Result = False Then
  26.             Console.WriteLine(InputString & " is not converted to Integer" & vbCrLf)
  27.         Else
  28.             Console.WriteLine(InputString & " is converted to Integer : " & IntegerResult & vbCrLf)
  29.         End If
  30.  
  31.         InputString = "12345.111"
  32.         Result = Double.TryParse(InputString, DoubleResult)
  33.         If Result = False Then
  34.             Console.WriteLine(InputString & " is not converted to Double : " & vbCrLf)
  35.         Else
  36.             Console.WriteLine(InputString & " is converted to Double : " & DoubleResult & vbCrLf)
  37.         End If