Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# integer validation compactframework

Using the .Net Compact Framework 2.0, how can I validate an integer (Int32.TryParse is not supported on the Compact Framework)?

like image 743
user690932 Avatar asked Jan 20 '23 07:01

user690932


2 Answers

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;
    }
}
like image 151
ctacke Avatar answered Jan 29 '23 22:01

ctacke


  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

like image 28
Ben Voigt Avatar answered Jan 29 '23 20:01

Ben Voigt