Problem
When you try to convert a string to an integer with int.Parse() (or Convert.ToInt32()), you get the following exception:
System.OverflowException: Value was either too large or too small for an Int32.
The problem is the integer value in the string can’t fit in the 32-bit integer. Int32 (int) can only hold values between -2147483648 (Int32.MinValue) and 2147483647 (Int32.MaxValue). You can either use a larger integer type or use int.TryParse().
Solution 1 – Use a larger integer type
When you’re dealing with large values that won’t fit in an Int32, use a larger integer type such as Int64 (long) or BigInteger. Here’s an example:
var long1 = long.Parse("9223372036854775807");
var long2 = long.Parse("-9223372036854775808");
var bigInt1 = System.Numerics.BigInteger.Parse("9999999999999999999999999999999999999999");
var bigInt2 = System.Numerics.BigInteger.Parse("-9999999999999999999999999999999999999999");
Code language: C# (cs)
Note: Unsigned integer types are also an option if you’re only dealing with positive numbers.
Integer max sizes
For reference, the following table shows the min and max values for integer types starting with Int32. Use whichever integer type can handle your expected range of values.
Type | Min Value | Max Value | Min / Max Constants |
Int32 (int) | -2147483648 | 2147483647 | Int32.MinValue Int32.MaxValue |
UInt32 (uint) | 0 | 4294967295 | UInt32.MinValue UInt32.MaxValue |
Int64 (long) | -9223372036854775808 | 9223372036854775807 | Int64.MinValue Int64.MaxValue |
UInt64 (ulong) | 0 | 18446744073709551615 | UInt64.MinValue UInt64.MaxValue |
BigInteger | No practical limit | No practical limit |
Solution 2 – Use int.TryParse()
You can filter out invalid input by using int.TryParse() instead of int.Parse(). This returns false if the parsing fails instead of throwing an exception. Here’s an example:
var input = "9223372036854775807";
if (int.TryParse(input, out int a))
{
//use the valid integer
}
else
{
//decide what to do about invalid input (ignore, return a default, etc...)
}
Code language: C# (cs)
This is cleaner than using a regular try/catch with OverflowException (and all the other parsing exceptions).