Integer.Parse: Convert String to IntegerConvert Strings to Integers with the Integer.Parse and TryParse Functions.
This page was last reviewed on Aug 13, 2021.
Integer.Parse. A String sometimes contains digits. It is converted to an Integer in VB.NET with Integer.Parse—this is a powerful function.
There are several Integer parsing Functions in .NET. TryParse is often the best choice. We choose between these functions and use them in an optimal way.
First example. We see a simple example that converts a String containing digits into an actual Integer value. An Integer is often more convenient for a program.
Step 1 We declare a String with the contents "2020." This is not an Integer, but a representation of 2 digits in character form.
Step 2 We call Integer.Parse. This Function receives the text string and returns the Integer form of it.
Module Module1 Sub Main() ' Step 1: an input string. Dim text As String = "2020" ' Step 2: convert string to integer value. Dim value As Integer = Integer.Parse(text) Console.WriteLine(value) End Sub End Module
Integer.TryParse. This is a programmatic way to both test for integers and parse them in a single pass. When parsing integers, we want to avoid exceptions and gracefully handle errors.
Detail To accomplish this, we use the Integer.TryParse shared method. TryParse provides a tester-doer pattern to parsing.
Here This example calls the Integer.TryParse function, which will not throw an exception if the input string is invalid.
Detail It will return false. The example further shows how to test the return value of TryParse.
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
ToInt32. Here we use Convert.ToInt32 to convert a String to an int. Internally, Convert.ToInt32 is implemented with Integer.Parse. It throws on invalid input.
And The String is converted to an Integer, in the same way as with Integer.Parse. The Integer 500 is written to the Console here.
Module Module1 Sub Main() ' The input string you want to convert to Integer. Dim text As String = "500" ' Convert to an Integer. Dim value As Integer = Convert.ToInt32(text) ' Writes 500 to screen. Console.WriteLine(value) End Sub End Module
FormatException. Here we see what happens when you try to parse a String that does not contain a numeric value as an Integer. You will get a System.FormatException.
Detail This exception simply means that Integer.Parse was passed a String in an invalid format.
Tip We can handle this problem with exception-handling. But for performance it is better to use Integer.TryParse.
Module Module1 Sub Main() ' First entry try block. Try ' Parses invalid string and throws. Dim x As String = "bad" Dim y As Integer = Integer.Parse(x) Catch ex As Exception ' Write exception to screen. Console.WriteLine(ex) End Try End Sub End Module
System.FormatException: Input string was not in a correct format.
Benchmark, ToInt32. Integer parsing is done in many VB.NET programs. Should we prefer a Function like Convert.ToInt32, or the Integer.Parse Function?
Version 1 This version of the code calls Convert.ToInt32 to convert the 4-character string to an Integer.
Version 2 This code uses Integer.Parse to perform the conversion. Like version 1, it should receive the Integer 1234.
Result Convert.ToInt32 is slower than a call to Integer.Parse. It contains some extra branch instructions.
Module Module1 Sub Main() Dim m As Integer = 100000 Dim text As String = "1234" ' Version 1: use Convert.ToInt32. Dim s1 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim result As Integer = Convert.ToInt32(text) Next s1.Stop() ' Version 2: use Integer.Parse. Dim s2 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim result As Integer = Integer.Parse(text) Next s2.Stop() Dim u As Integer = 1000000 Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) End Sub End Module
79.19 ns Convert.ToInt32 76.20 ns Integer.Parse
Benchmark, invalid string. With Integer.TryParse we handle invalid strings much faster than with Integer.Parse. Consider this benchmark. We try to parse the string "xyz."
Version 1 The "A" function is called and the Integer.Parse method throws an Exception each time.
Version 2 The TryParse method is called. No exceptions are thrown. But the same result is returned.
Result The Integer.TryParse method is many times faster than the Integer.Parse method when dealing with invalid string data.
Module Module1 Sub Main() Dim m As Integer = 100000 Console.WriteLine(A()) Console.WriteLine(B()) Dim s1 As Stopwatch = Stopwatch.StartNew ' Version 1: use Try, Catch with Integer.Parse. For i As Integer = 0 To m - 1 A() Next s1.Stop() Dim s2 As Stopwatch = Stopwatch.StartNew ' Version 2: use Integer.TryParse. For i As Integer = 0 To m - 1 B() Next s2.Stop() Dim u As Integer = 1000000 Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) End Sub Function A() As Integer ' Use Parse on an invalid string, but handle the exception. Dim result As Integer Try result = Integer.Parse("xyz") Catch ex As Exception result = 0 End Try Return result End Function Function B() As Integer ' Use TryParse on an invalid string. Dim result As Integer Integer.TryParse("xyz", result) Return result End Function End Module
0 0 23907.64 ns Integer.Parse, Try, Catch 49.87 ns Integer.TryParse
Tester-doer. This pattern is used for TryParse. First, the code sees if the parsing will succeed. If this test succeeds, it will do the parse. This avoids costly exceptions.
Detail Sometimes code that uses Strings where Integers are better. We can convert Strings that contain Integers to actual Integers.
And This can improve compatibility. It can lead to improved error-checking. Integers are easier to test.
A recommendation. Integer.TryParse typically simplifies your code. Not only that, but it leads to more robust and crash-proof code. I typically recommend TryParse.
A summary. Integer.Parse and TryParse are helpful. These functions are the most important and widely-used ones for converting integers to strings.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 13, 2021 (image).
© 2007-2023 Sam Allen.