Using the .Net Compact Framework 2.0, how can I validate an integer (Int32.TryParse
is not supported on the Compact Framework)?
What do you mean by "validate"? Do you mean parse without throwing?
static bool TryParse(string s, out int value)
{
try
{
value = int.Parse(s);
return true;
}
catch
{
value = 0;
return false;
}
}
static bool TryParseImpl(string s, int start, ref int value)
{
if (start == s.Length) return false;
unchecked {
int i = start;
do {
int newvalue = value * 10 + '0' - s[i++];
if (value != newvalue / 10) { value = 0; return false; } // detect non-digits and overflow all at once
value = newvalue;
} while (i < s.Length);
if (start == 0) {
if (value == int.MinValue) { value = 0; return false; }
value = -value;
}
}
return true;
}
static bool TryParse(string s, out int value)
{
value = 0;
if (s == null) return false;
s = s.Trim();
if (s.Length == 0) return false;
return TryParseImpl(s, (s[0] == '-')? 1: 0, ref value);
}
Demo: http://ideone.com/PravA
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