String
, IntegerA String
can be converted to an Integer. The String
stores the digits of a number. Some functions available do not handle invalid cases well.
We show the Integer.TryParse
method as a solution to handling invalid data. It does not cause performance problems with exceptions.
Here, the input String
is correctly formatted. It contains the number "123456" stored as characters. We declare the local variable "i" and then use Integer.TryParse
in an If
-expression.
Integer.TryParse
returns True, we have an actual Integer. We show this by dividing the Integer by two.String
format. A string
cannot be divided.Module Module1 Sub Main() ' Input String. Dim value As String = "123456" ' Use Integer.TryParse. Dim i As Integer If (Integer.TryParse(value, i)) Then Console.WriteLine("Integer: {0}", i) Console.WriteLine("Half: {0}", i / 2) End If End Sub End ModuleInteger: 123456 Half: 61728
Integer.TryParse
does not cause performance problems when an invalid number is encountered. This method is usually considered the best parsing method.
TryParse
will tell you if you have an invalid number.Integer.TryParse
is probably best unless you have serious performance demands.We converted a String
holding digit characters into an actual Integer. Integer.TryParse
(and other TryParse
functions) is versatile and useful.