How do I convert a string to an integer in C#?
Do something like:
var result = Int32.Parse(str);
int i;
string whatever;
//Best since no exception raised
int.TryParse(whatever, out i);
//Better use try catch on this one
i = Convert.ToInt32(whatever);
If you're sure it'll parse correctly, use
int.Parse(string)
If you're not, use
int i;
bool success = int.TryParse(string, out i);
Caution! In the case below, i
will equal 0, not 10 after the TryParse
.
int i = 10;
bool failure = int.TryParse("asdf", out i);
This is because TryParse
uses an out parameter, not a ref parameter.
string varString = "15";
int i = int.Parse(varString);
or
int varI;
string varString = "15";
int.TryParse(varString, out varI);
int.TryParse
is safer since if you put something else in varString
(for example "fsfdsfs") you would get an exception. By using int.TryParse
when string can't be converted into int it will return 0
.
bool result = Int32.TryParse(someString, out someNumeric)
This method will try to convert someString
into someNumeric
, and return a result
depends if the conversion is successful, true
if conversion is successful and false
if conversion failed. Take note that this method will not throw exception if the conversion failed like how Int32.Parse
method did and instead it returns zero for someNumeric
.
For more information, you can read here:
https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
&
How to convert string to integer in C#
4 techniques are benchmarked here.
The fastest way turned out to be the following:
y = 0;
for (int i = 0; i < s.Length; i++)
y = y * 10 + (s[i] - '0');
"s" is your string that you want converted to an int. This code assumes you won't have any exceptions during the conversion. So if you know your string data will always be some sort of int value, the above code is the best way to go for pure speed.
At the end, "y" will have your int value.