John John - 3 months ago 9
C# Question

check ALL arguments in c# that they can be numeric

I am writing a small console application in C# and it requires two numeric parameters/arguments to be passed to it. I am checking for no params, more than 2 params, if two params. I am also converting those params if 2 returned to numeric for calculations I'm doing. One thing I'm not doing is verifying what's being passed is a number so assume program will crap out if I pass a letter. Is there a look routing I can just run to verify the params passed are in deed able to be numbers? I can handle the kick out from there but curious how you check if an argument CAN be a number or not.

Thanks.

JR

Answer

Here's one way;

static void Main(string[] args)
    {
        foreach (var arg in args)
        {
            int asInt;
            // Returns "true" if arg can be parsed as an int and false otherwise;
            // If you want to allow doubles you can also try double.TryParse in a similar manner
            if (int.TryParse(arg, out asInt))
            {
                // Handle
            }
            // Failed to parse argument as an int
            else
            {
                throw new ArgumentException("arg not an int");
            }
        }
 }

You could also use a Regex:

    static void Main(string[] args)
    {
        // Make sure this can is either an int or a double
        var regex = new Regex(@"^-?(([0-9]+)|([0-9]+\.[0-9]+(e[0-9]+)?))$");

        foreach (var arg in args)
        {
            if (!regex.IsMatch(arg))
                throw new ArgumentException("arg " + arg + " is not an int or double");
        }
    }

Note a few important features of this regex:
- The "@" literal symbol in front of the regex string
- The ^ and $ to mark the beginning and end of lines - i.e. the string must contain only a number or only a double
- This bans empty strings as well
Edit: I edited the Regex to optionally allow for something like "1.0e100" or "-123", which, as pointed out in the comments, are also perfectly valid ints and doubles. Also, as pointed out in the comments, it's probably better to use int.TryParse or double.TryParse rather than reinventing the wheel.

Comments