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 would attempt to parse, if it fails, then attempt to parse a higher-capacity value. If the higher capacity value passes parsing, then you know it's out of range. If it fails as well, then it's bad input.
Unfortunately, I don't think there's a way to do this generically for any type; you'd have to write an implementation for all types. So for example, what do do for
Int64
? Maybe useBigInteger
instead:EDIT:
double
floating point values may be more fun since AFAIK, there's no "BigDecimal" and you may have to also account for values that approach 0 at the very extreme (not sure about that). Possibly you could do a variation on theBigInteger
check but you might also have to account for decimal points (probably a simple regex would be best here to have only numbers, an optional negative sign, and only one at most decimal point). If there are any decimal points, you'd have to truncate them out and simply check the integer portion of the string.EDITx2: Here's a pretty ugly implementation for checking
double
values too:But honestly, at this point I think we've just gone off the deep end. Unless you have some real performance bottleneck, or your application has out-of-range values inputted frequently, you might be better off just catching them the odd time it happens as in this answer or perhaps more simply, applying a regex to the input. In my last example, I may have as well just quit after doing the regex anyway (but I don't know off the top of my head if the
TryParse
implementations are more lenient, allowing for exponential/scientific notation. If so, the regex would have to cover these as well)