VB.NET Integer.TryParse

String type

Integer.TryParse is robust. When parsing integers, we want to avoid exceptions and gracefully handle errors. To accomplish this, we use the Integer.TryParse shared method. TryParse provides a tester-doer pattern to parsing.

Example

Note

This example demonstrates the Integer.TryParse function, which is 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 to test the return value of TryParse.

If Then
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
Main method

The first String is not a valid integer. Integer.TryParse then returns False. The If Not statement then assigns the number to -1. The Integer is either set to the number in the String, or -1 if there is no valid number in the String.

Summary

The VB.NET programming language

Parsing integers in the VB.NET language may seem less intuitive with the Integer.TryParse method. But this approach typically simplifies your code.
Not only that,
but it leads to more robust
and crash-proof code.

Integer.Parse

VB.NET: Number