3

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);
Vivian River
  • 31,198
  • 62
  • 198
  • 313

3 Answers3

8

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
}
configurator
  • 40,828
  • 14
  • 81
  • 115
5

You can do something like

int dummy;
if (int.TryParse(foo, out dummy)) {
   //...
}
Paulo Santos
  • 11,285
  • 4
  • 39
  • 65
4

Use Int32.TryParse

e.g:

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

if (Int32.TryParse(foo, out fooInt ))     
    doStuff(fooInt); 
else     
    doStuff(null); 
Chandu
  • 81,493
  • 19
  • 133
  • 134