VB.NET Convert.ToInt32 Function

The VB.NET programming language

You want to convert a String into its Integer representation in your VB.NET program. Although there are many possible ways to do this, we show here the Convert.ToInt32 function and also produce benchmarks.

Example

Note

This simple example shows how to use the Convert.ToInt32 function. The String object contains four characters: "1234". The result Integer from Convert.ToInt32 contains the number 1234. We show that this is a number by subtracting one from it, which yields 1233.

This VB program uses the Convert.ToInt32 Function from the System namespace.

Program that uses Convert.ToInt32 [VB.NET]

Module Module1
    Sub Main()
	Dim text As String = "1234"
	Dim i As Integer = Convert.ToInt32(text)
	Console.WriteLine(i)
	Console.WriteLine(i - 1)
    End Sub
End Module

Output
1234
1233

Convert.ToInt32 versus Integer.Parse. The difference between Convert.ToInt32 and Integer.Parse lies in the way the two methods handle errors. If you pass a String with a value of Nothing to Convert.ToInt32, it will return 0. If you do that with Integer.Parse, an Exception will be thrown.

Benchmark

Performance optimization

Convert.ToInt32 is slower than a simple call to Integer.Parse. This is because it contains some branch instructions and also has extra method invocation. Furthermore, to demonstrate this, this benchmark times a call to Convert.ToInt32 and Integer.Parse. The call to Convert.ToInt32 was over 10 nanoseconds slower.

Sample that uses Convert.ToInt32 [VB.NET]

Dim text As String = "1234"
Dim i As Integer = Convert.ToInt32(text)

Sample that uses Integer.Parse [VB.NET]

Dim text As String = "1234"
Dim i As Integer = Integer.Parse(text)

Benchmark result
    Ten million iterations.

138.53 ns
126.76 ns

Summary

We looked at the Convert.ToInt32 function in the VB.NET language. This function is very similar to Integer.Parse. It handles Nothing arguments without throwing an error. Typically, Integer.Parse and Integer.TryParse are more efficient and also more widely used, thus preferable.

Integer.Parse Function Examples Integer.TryParse VB.NET Tutorials
.NET