Pregunta

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

int defaultTop;
displayTop = (Int32.TryParse(DisplayTop, out defaultTop) ? Convert.ToInt32(DisplayTop) : 1000 );
¿Fue útil?

Solución

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

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top