14 April 2011

C# Convert String to Integer

Converting string to int is simple in c#. There are two comman ways to convert string to int.
  • Convert.ToInt32
  • Int32.TryParse
Here is the screen shot of our string to int converter sample application:

Note that our integer number must be between −2,147,483,648 and +2,147,483,647 range.

The c# source code to convert string to integer:
private void btnConvert_Click(object sender, EventArgs e)
int numValue = 0;
string strValue = string.Empty;

strValue = tbInput.Text.Trim();

numValue = Convert.ToInt32(strValue);
lblResult.Text = numValue.ToString();
catch (Exception exc)
tbInput.Text = string.Empty;
lblResult.Text = string.Empty;
MessageBox.Show("Error occured:" + exc.Message);

private void btnTryParse_Click(object sender, EventArgs e)

private void ConvertToIntTryParse()
int numValue = 0;
bool result = Int32.TryParse(tbInput.Text, out numValue);
if (true == result)
lblResult.Text = numValue.ToString();
MessageBox.Show("Cannot parse string as int number");

I think IntTryParse is better to convert string to int, because it handles the parse error inside and returns bool value if the string is parsable to int.
IntTryParse return boolean value, so that if it parses the string it returns true, else returns false.

Note the parsing string with Convert.ToInt32 may cause a FormatException if the parse string value is not suitable.


outofmemoryerror in java said...

There is another way of converting String into Integer which uses Integer.valueOf(), this is also a static method and can be used as utility for string to int conversion.
source: String to Int to String conversion examples

Anonymous said...

I know this post has been answered already, but for those who are looking for benchmarks, he benchmarks several different ways to convert a string to an int:


What's interesting is the fastest way isn't using any of the native C# methods Convert.ToInt32(), int.TryParse(), or int.Parse().

Definitely worth a read for those that are curious.