Hans Hans - 1 year ago 161
C# Question

Convert String to INT with Int.Parse()

I have a text box that firstly received 9 numbers which automatically would be strings then that would be loaded to my DB the conversion to INT used is


So I get a request to update the numbers to 10, I changed all values but there is an error with the
it says the value is either too big or too small.

I´ve tried other methods but no solution, is there another way to convert it to INT or whats wrong with



public static int TransferClient(string NRIFActual, string NRIFNuevo)
int nResult = 0;
nResult = ws.TransferClient(int.parse(NRIFActual), int.Parse(NRIFNuevo));
catch (System.Net.WebException ex)
throw new Exception(ex.Message);
return nResult;

Notice that I need the same variable name because it is used in s web service, is there a way to just convert it to INT64 like the int.parse()?

Answer Source

You probably get OverflowException because the value that an int(Int32) can store is between -2,147,483,648 and 2,147,483,647.

1) Verify that the string input you pass is the correct one.

2) If the users shouldn't insert number this high try to add a validation to the input(text box)

3) If the user will(can) insert bigger numbers you should use a type that can store an higher value -> long(Int64) should be enough(The range is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807), if not go bigger -> you will find a list with C# types here : https://msdn.microsoft.com/ro-ro/library/ya5y69ds.aspx

Tip: use TryParse method instead of Parse(for any type you will use). This method will return a bool that states if the conversion succeeded or failed and the actual conversion in output parameter. This will make the exception handling much easier.

Edit after Hans comment:

To keep the solution simple and not dive in another topics you should do something like this:

string input = "92233720368547758071";
long result;
if (!long.TryParse(input , out result))
     /*error handling */
    /*Continue the flow of your program*/

*The input may came from anywhere. This is just for example purpose.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download