VB.NET Convert String to Integer

Question and answer

How can you convert a String that stores the digits of a number to an actual Integer in your VB.NET program? Some functions available do not handle invalid cases well. We show the Integer.TryParse method as a solution to this problem.

This VB program converts a String to an Integer. It uses Integer.TryParse.

Example

Let's get started with this simple demonstration program. The input String here is correctly formatted: it contains the number "123456" stored as characters. We declare the local variable i (As Integer) and then use Integer.TryParse in an If-expression.

Integer.TryParse
Program that converts String to Integer [VB.NET]

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 Module

Output

Integer: 123456
Half:    61728

Results. After Integer.TryParse returns True, we have an actual Integer. We show this by dividing the Integer by two. This would not be possible with a number stored in String format.

Best way to parse?

This section provides information

I have often wondered the best way to parse numbers in the .NET Framework. Overall, Integer.TryParse (and its equivalents) is what I feel is the best solution. It does not cause performance problems when an invalid number is encountered. You do not have to write custom algorithms. It will tell you if you have an invalid number. Integer.TryParse is probably best unless you have serious performance demands.

Summary

The VB.NET programming language

We looked at how you can convert a String holding digit characters into an actual Integer in the VB.NET language. There are many parsing functions available in the .NET Framework, but Integer.TryParse (and other TryParse functions) is one of the most versatile and useful.

VB.NET Tutorials
.NET