In this article, we are going to talk about how to convert string to int in C#.
Int is an alias of Int32, and defines an integer number in range from -2,147,483,648 to +2,147,483,647. Setting a value of an int variable that is out of this range, will produce a “System Overflow Exception”.
Converting a string to int is a common scenario. For example, we read a value from an external source as a string, convert it into a number, and then use it in a calculation. In addition, we can use the built-in functions or write our own conversion method.
Let’s start.
Convert String to Int Using Int32.Parse()
First, let’s create a console application, and define the values we are going to convert from and convert into:
var stringValue = "3"; var number = 0;
In the first line, we define stringValue
variable with the value of “3” which we will use in the conversions. In the second line, we define a number
variable where we are going to store the results of the conversions:
number = int.Parse(stringValue); Console.WriteLine($"Converted '{stringValue}' to {number} using 'int.Parse()'");
Using the Int.Parse()
method we convert the string “3” to number 3 and write the result in the console.
If we try to convert an empty string or text that can not be interpreted as a number with the Int.Parse()
method, it will throw a FormatException
with the message:
Input string was not in a correct format.
That may be something we want, but if it’s not there’s an alternative.
Convert String to Int Using Int32.TryParse()
This method is checking if a string
is a valid number and returns a boolean
value without throwing any exceptions. If conversion to int
is possible, the number is set in the provided out
variable:
int.TryParse(stringValue, out number); Console.WriteLine($"Converted '{stringValue}' to {number} using 'int.TryParse()'");
We try to convert the value of stringValue
variable using the Int32.TryParse()
method. Since the provided value is “3” which can be converted, we set the out number
variable to 3 and we write the result in the console. This method returns true if the conversion succeeds. Otherwise, it returns false and sets the out number
variable to 0 without throwing an error.
To read more about the Parse and TryParse methods, you can read our Parse and TryParse in C# article.
Convert String to Int Using Convert.ToInt32()
We use this method to convert a string, into int
. When we pass an invalid string as a parameter, like a non-empty or alphanumeric string, the method will throw FormatException
. However, for passed null value as a parameter, it converts it to 0, without throwing an exception:
number = Convert.ToInt32(stringValue); Console.WriteLine($"Converted '{stringValue}' to {number} using 'Convert.ToInt32()'");
Using the Convert.ToInt32()
method we convert the value of stringValue
variable into number
and write the result in the console.
Using a Custom Method CustomConvert.Parse()
We can also build our own simplified custom method that converts a string
into an int
:
public static class CustomConvert { public static int Parse(string strVal) { var num = 0; for (var i = 0; i < strVal.Length; i++) { num = num * 10 + (strVal[i] - '0'); } return num; } } number = CustomConvert.Parse(stringValue); Console.Write($"Converted '{stringValue}' to {number} using 'CustomConvert.Parse()'");
We use this code to convert a string
value to an integer
in the simplest way possible. We do not use any of the extra features that the built-in methods provide, like whitespace trimming, null-checks, or culture formatting.
We are taking the advantage of the good performances when converting a character into its ASCII code. For example ‘0’ has an ASCII code of 48, ‘1’ – 49, ‘2’ – 50, ‘3’ – 51, etc. And with a simple calculation, we can efficiently convert one character into a number.
In the code, we start by declaring a CustomConvert.Parse()
method. Inside the method, we define a variable named num
and initialize it with 0. Then, for each character in the input string, we multiply the num
variable with 10, convert the character into its ASCII code, subtract the ASCII code value of ‘0’ and store the result back into the num
variable.
We call the custom function that converts the provided string value of “3” into number 3 and writes the result in the console.
Benchmark
In order to understand the difference in performance between all of the above methods, we will measure their execution time using BenchmarkDotNet:
| Method | Mean | Error | StdDev | |------------------------ |---------:|----------:|----------:| | BenchmarkIntParse | 8.441 ns | 0.1723 ns | 0.1527 ns | | BenchmarkIntTryParse | 9.095 ns | 0.2101 ns | 0.2064 ns | | BenchmarkConvertToInt32 | 9.096 ns | 0.2092 ns | 0.1957 ns | | BenchmarkCustomConvert | 1.095 ns | 0.0378 ns | 0.0335 ns |
As we can see from the benchmarks, our custom code outperforms the built-in conversion methods and runs 8 times faster! The in-built methods perform roughly the same.
However, that doesn’t mean that we should always create a custom code for converting string
to int
. But only when it will make a significant difference in performance. If our string
input is not a valid number all the time, then we can use the built-in conversion methods.
Conclusion
In this article, we’ve learned about different methods to convert string to int. We’ve compared the differences and we’ve shown which approach has the best performance.