How to determine if a value in Request.Form is a number? (WITH#)

Suppose I have to call a function with the following signature: DoStuff (Int32?)

I want to convey the doStuffvalue that is read from Request.Form. However, if the passed value is empty, missing or not a number, I want doStuffan empty argument to be passed. This should not lead to an error; this is an operation.

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

var foo = Request.Form["foo"];
if (foo is a number)
    doStuff(foo);
else
    doStuff(null);
+3
source share
3 answers

If you want to check if this is an integer, try to parse it:

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

You can do something like

int dummy;
if (int.TryParse(foo, out dummy)) {
   //...
}
+5
source

Int32.TryParse

:

var foo = Request.Form["foo"]; 
int fooInt = 0;

if (Int32.TryParse(foo, out fooInt ))     
    doStuff(fooInt); 
else     
    doStuff(null); 
+4

All Articles