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);
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
}
You can do something like
int dummy;
if (int.TryParse(foo, out dummy)) {
//...
}
Use Int32.TryParse
eg:
var foo = Request.Form["foo"];
int fooInt = 0;
if (Int32.TryParse(foo, out fooInt ))
doStuff(fooInt);
else
doStuff(null);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.