The fastest SIN validator

The fastest implementation I’ve seen of a validator for a Canadian Social Insurance number is from hackcanada.

I’ve rewritten his JavaScript code here in C# with a few guard clauses at the top. Enjoy!
================================

private static bool ValidateSIN(string sin)
{
    int dummy;
    if (!Int32.TryParse(sin, out dummy)) return false;
    if (sin.Length != 9) return false;

    int s = 0;
    for (int i = 0; i < 9; i++)
    {
        int x = Convert.ToInt32(sin.Substring(i, 1));
        if (i % 2 != 0)
        {
            if ((x << 1) > 9)
            {
                s += ((x << 1) - 9);
            }
            else
            {
                s += (x << 1);
            }
        }
        else
        {
            s += x;
        }
    }
    return (s % 10 == 0);
}

EDIT: Neil correctly pointed out I was missing a null check as my first statement; I was checking (sin.Length != 9) first.  I’ve changed it and decided to do the Int32.TryParse() first before checking for length.  According to Reflector, System.Int32.TryParse(string s, out int result) calls the internal method System.Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) which in turn calls System.Number.TryStringToNumber(string str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal) which does a null check. :P

I like Rick Brewster’s fluent approach to parameter validation using .NET 3.0 and higher.  It’s pretty slick.

This entry was posted on Friday, December 5th, 2008 at 10:22 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Related Posts

One Response to “The fastest SIN validator”

  1. Hi Vince,

    You are missing a null check if your first if statement.

    If should probably be the following:

    if (string.IsNullOrEmpty || sin.Length != 9) return false;

Leave a Reply