开发者

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);


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

e.g:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜