Last Updated on March 15, 2022
In this article, we will quickly show 3 different ways to convert a string containing a numeric value to a 32-bit signed integer (i.e. C# convert string to int).
C# Convert string to int with the Int32.Parse method
The first method that you can use to convert a string to an integer is the Int32.Parse method. The Parse method is available for most numeric types. In fact, it provides an easy way to developers to convert a string to the specified numeric type.
If the conversion fails, the Parse method will simply throw an exception. Therefore, you need to use this method inside a try-catch block.
Here is a sample code where we call the different overloads of the Parse method:
This program gives the following output:
C# Convert string to int with the Int32.TryParse method
The Int32.TryParse method is similar to the Int32.Parse method, except the fact that the TryParse method does not throw an exception when the conversion fails. Basically, the return value for the TryParse method is a Boolean, therefore it simply returns false when the conversion fails. In addition, in order to get the converted integer, you need to pass an Int32 variable to that method as an argument with the out keyword.
Here is a sample code where we call the different overloads of the TryParse method:
And the console output when you execute this code:
What about the Convert.ToInt32 method?
The Convert.ToInt32 method is part of the static Convert class, which contains a set of methods that facilitate conversions between built-in types in C#. This method can also throw exceptions, like the Int32.Parse method. As a matter of fact, the documentation explicitly says that the Convert.ToInt32 is equivalent to calling Int32.Parse with the current culture-specific format information.
Here is a sample code that uses this method:
And running this code gives the following output:
In conclusion, all these 3 methods can be used to convert a numeric string to an integer, depending on your preference.
I hope you enjoyed this article from our fundamentals series. You can find other articles with the fundamental tag here.