
Integer.TryParse is robust. When parsing integers in the VB.NET programming language, you want to avoid exceptions and handle errors gracefully. To accomplish this, you can use the Integer.TryParse shared method, which provides a tester-doer pattern to parsing.
This VB example program demonstrates the Integer.TryParse Function.
This example demonstrates the Integer.TryParse function, which is very useful when you are not certain the input String is valid. It will not throw an exception if the input string is invalid. Instead, it will return false. The example further shows how you can test the return value of TryParse.
Program that uses TryParse [VB.NET]
Module Module1
Sub Main()
' An invalid number string
Dim s As String = "x"
' Try to parse it. If it isn't a number, use -1
Dim num As Integer
If Not Integer.TryParse(s, num) Then
num = -1
End If
' Writes -1 to the screen
Console.WriteLine(num)
End Sub
End Module
Output
-1
Explanation. The Main entry point is defined above, and the first String is not a valid integer. When we send it to Integer.TryParse, the function returns False. The If Not statement then assigns the number to -1. The effect is that the Integer is either set to the number in the String, or -1 if there is no valid number in the String.
Although parsing integers in the VB.NET language may seem less intuitive with the Integer.TryParse method, this approach typically simplifies your code. Not only that, but it leads to more robust and crash-proof code, furthering your goal of stability and relative invulnerability.
Integer.Parse Function Examples VB.NET Tutorials