Converting string to integer

suggest change

There are several ways to convert a string to an integer:

  1. Convert.ToInt16();
  2. Convert.ToInt32();
  3. Convert.ToInt64();
  4. int.Parse();

These methods throw FormatException when the text is not an integer, and OverflowException when it does not fit the target type. A try/catch can handle that failure.

Explanation with Examples:

So, let our input be:

string inputString = "10.2";

Example 1: Convert.ToInt32()

int convertedInt = Convert.ToInt32(inputString); // Failed to Convert 
// Throws an Exception "Input string was not in a correct format."

Note: Same goes for the other mentioned methods namely - Convert.ToInt16(); and Convert.ToInt64();

Example 2: int.Parse()

int convertedInt = int.Parse(inputString); // Same result: "Input string was not in a correct format."

How do we circumvent this?

As told earlier, for handling the exceptions we usually need a try..catch as shown below:

try
{
    string inputString = "10.2";
    int convertedInt = int.Parse(inputString);
}
catch (Exception Ex)
{
    //Display some message, that the conversion has failed.         
}

But, using the try..catch everywhere will not be a good practice, and there may be some scenarios where we wanted to give 0 if the input is wrong, (If we follow the above method we need to assign 0 to convertedInt from the catch block). To handle such scenarios we can make use of a special method called .TryParse().

TryParse does not throw for a bad format. It writes the converted value to the out parameter and returns true when the conversion succeeds, or false when it fails. On failure the out value is 0.

Usage 1: Store the return value in a Boolean variable

int convertedInt;
bool isSuccessConversion = int.TryParse(inputString, out convertedInt);

Check isSuccessConversion after the call. If it is false, convertedInt is 0. You can ignore the return value when 0 is an acceptable result for a failed conversion.

Usage 2: Check the return value with if

if (int.TryParse(inputString, out convertedInt))
{
    // convertedInt will have the converted value
    // Proceed with that
}
else 
{
 // Display an error message
}

Usage 3: Without checking the return value you can use the following, if you don’t care about the return value (converted or not, 0 will be ok)

int.TryParse(inputString, out convertedInt);
// use the value of convertedInt
// But it will be 0 if not converted

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents