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();

try
{
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)
{
ConvertToIntTryParse();
}

private void ConvertToIntTryParse()
{
int numValue = 0;
bool result = Int32.TryParse(tbInput.Text, out numValue);
if (true == result)
lblResult.Text = numValue.ToString();
else
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.