Search code examples
c#asp.netstringstring-parsingrequest.form

How can I tell if a value in Request.Form is a number? (C#)


Suppose I must call a function with the following signature: doStuff(Int32?)

I want to pass to doStuff a value that is read from Request.Form. However, if the value passed in is blank, missing, or not a number, I want doStuff to be passed a null argument. This should not result in a error; it is a operation.

I have to do this with eight such values, so I would like to know what is an elegent way to write in C#

var foo = Request.Form["foo"];
if (foo is a number)
    doStuff(foo);
else
    doStuff(null);

Solution

  • If you want to check whether or not it's an integer, try parsing it:

    int value;
    if (int.TryParse(Request.Form["foo"], out value)) {
        // it's a number use the variable 'value'
    } else {
        // not a number
    }