I have the following piece of code which attempts to determine whether a given string is a valid integer. If it’s an integer, but not within the valid range of Int32, I need to know specifically whether it’s greater than Int32.MaxValue or less than Int32.MinValue.
try
{
return System.Convert.ToInt32(input);
}
catch (OverflowException)
{
return null;
}
catch (FormatException)
{
return null;
}
Convert.ToInt32 will throw the OverflowException if it’s not in the range of acceptable values, but it throws the same exception for both greater than and less than. Is there a way to determine which one it is aside from parsing out the text of the exception?
As you’re using .NET 4, you could use
BigInteger– parse to that, and then compare the result with theBigIntegerrepresentations ofint.MaxValueandint.MinValue.However, I would urge you to use
TryParseinstead of catching an exception and using that for flow control.