C#: How to convert string to int in C#
Introduction:
In this article i will explain how to convert string to integer in C#. And how many ways we can convert string to integer.
You can convert a string to a integer by using ToInt32(String)
method.
Example:
string str = "23"; int a = Convert.ToInt32(str);
Output:
23
Another way of converting a string to an int is through the Parse
or TryParse
methods of the System.Int32 struct.
Parse Example:
int numVal = Int32.Parse("-105"); Console.WriteLine(numVal);
Output:
-105
Example:
try { int m = Int32.Parse("abc"); } catch (FormatException e) { Console.WriteLine(e.Message); }
Output:
Input string was not in a correct format.
TryParse Example:
int j; bool result = Int32.TryParse("-105", out j); if (true == result) { Console.WriteLine(j); } else { Console.WriteLine("String could not be parsed."); }
Output:
-105
Note: TryParse returns true if the conversion succeeded and stores the result in the specified variable.
If you want to assign a default value instead of displaying error message when conversion fails use Ternary Operator along with TryParse
.
See the following examples:
Example:
int num; int result = Int32.TryParse("-105", out num) ? num : num;
Output:
-105
Example:
int num; int result = Int32.TryParse("abc", out num) ? num : num;
Output:
0
In the above example coversion fails. So, default value will be assigned to result.