No IsInteger() in C#?

Filed Under (development) by sith on 22-09-2008

Tagged Under : ,

(* this is a legacy post from one of my earlier blogging attempts, better formatting to come)

Unless I just can’t find it, there doesn”t seem to be a method to test a value for whether it is a valid integer (or at least could be turned into a valid integer) in C#. For example, today I needed a way to test a string value before converting it to an integer. The original code looked something like this:

int ConvertedNumber = Convert.ToInt32(TextBox1.Text);

Of course, we all see major issues with this line of code. What if TextBox1 doesn’t contain a number? What if TextBox1 doesn’t contain anything at all? It wouldn’t have been so bad if there was some protection around this, but there wasn’t. So…the need to write an IsInteger() method kicked in, and here’s what we came up with.

private static Regex _isNumber = new Regex(@"^\\d+$");

public static bool IsInteger(string theValue)
{
    bool result = false;

    Match m = _isNumber.Match(theValue);
    return m.Success;
}

During my initial testing, this looked like it was going to work perfectly, until I found the following scenario…what if a user typed in “01″? They would be expecting this to be converted to a “1″. Unfortunately, my regular expression couldn”t handle it, so the following hack is what we came up with:

public static bool IsInteger(string theValue)
{
    bool result = false;

    Match m = _isNumber.Match(theValue);
    result = m.Success;

    if (!result)
    {
        try
        {
            int ConvertedNumber = Convert.ToInt32(theValue);
            result = true;
        }
        catch
        {
            result = false;
        }
    }
    return result;
}

I really don’t like using try…catch to handle normal code flow, but I’m still learning regular expressions, and couldn’t figure out how to handle this scenario. If anybody out there wants to help me out, that would be appreciated. If I end up figuring it out myself, I’ll update this article.

Maybe this is a good time to start a common methods assembly. :)

NUnit and me

Filed Under (development) by sith on 21-09-2008

Tagged Under : , , , ,

So begins my latest foray into unit testing. Don’t ask why, but watching Conan The Barbarian has somehow inspired me to actually work at this a bit and finally try to figure out why/how to unit test.

I’m armed with a copy of Pragmatic Unit Testing in C# with Nunit, and a fresh attitude…so, here I go…

…after Conan is over. Oh yeah, if I do figure this out, maybe I’ll try putting together some tutorials that might help other monkeys out.