I have the following:
string outOfRange = "2147483648"; // +1 over int.MaxValue
Obviously if you have anything other than a number this will fail:
var defaultValue = 0;
int.TryParse(outOfRange, out defaultValue);
My question is, since this IS a number, and it WILL fail when you int.TryParse(), how do you tell that it failed because the string was out of the bounds of the container it's stored in?
I'd go with the Try/Catch solution for this scenario.
string outOfRange = "2147483648";
try
{
int.Parse(outOfRange);
}
catch (OverflowException oex)
{
}
catch (Exception ex)
{ }
I know that most people here would recommend avoiding this but sometimes we just have to use it (or we don't have to but it would just save us a lot of time).
here's a little post about the efficiency of Try/Catch.
can parse to decimal and then check range, avoids try/catch
string s = "2147483648";
decimal.Parse(s) > int.MaxValue;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With