Вопрос

Is it possible to check for negative number using Int32.TryParse?

int defaultTop;
displayTop = (Int32.TryParse(DisplayTop, out defaultTop) ? Convert.ToInt32(DisplayTop) : 1000 );
Это было полезно?

Решение

Why not use UInt32.TryParse(DisplayTop, out defaultTop)?

This will return true if the number is 0 or positive, and false if negative.

Другие советы

Try this

int defaultTop;
var isValidInt = Int32.TryParse(DisplayTop, out defaultTop);
displayTop = isValidInt && defaultTop >= 0 ? defaultTop : 1000;

You can't do that with TryParse alone, you will have to check the value of defaultTop independently. If you want it all in a single line you can try:

displayTop = ((Int32.TryParse(DisplayTop, out defaultTop) && defaultTop >= 0) ? defaultTop : 1000 );

Use Math.Max:

displayTop = Math.Max(1,(Int32.TryParse(DisplayTop, out defaultTop) ? Convert.ToInt32(DisplayTop) : 1000 ));

Granted, such a long expression is somewhat ugly, but it works.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top