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 (For开发者_StackOverflow社区matException)
{
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 the BigInteger
representations of int.MaxValue
and int.MinValue
.
However, I would urge you to use TryParse
instead of catching an exception and using that for flow control.
You could convert it to Int64
(i.e. long
) instead, and then do the comparison yourself. That will also eliminate an exception as control flow situation.
There is a very simple way to know if the input that threw an OverflowException (or gave a false if you used TryParse) is more than Int32.MaxValue or less than Int32.MinValue: a number less than Int32.MinValue will be a negative one, so its string representation will begin with a '-' !
The idea is:
bool isWrong = false;
bool isLarge = false;
if (!Int32.TryParse(rawValue, out int32Holder))
{
if (!Int64.TryParse(rawValue, out int64Holder))
{
isWrong = true;
}
else
{
isLarge = true;
}
}
精彩评论