Optimal way to check if query string is int?

The question that came up to one of my colleagues is the best way to check if the query string is int. I suggested using the classic Int.Parse and trying and catching, also suggested TryParse. In fact, I can not think of any other ways. Any ideas?

+3
source share
5 answers

Int32.TryParse will be your best choice.

+14
source

TryParse is probably the best choice, as it will allow you to use different formats for the string, and also tell you through a boolean regardless of whether it really is.

+2
source

Int32.TryParse. , , - .

+1

Probably not too useful, as you will most likely need the actual int (although it can be extended to do this). NOTE. I would not do that, but it IS an alternative way, which he did not think.

bool isNumeric = true;
foreach (char c in queryString) {
    if (!char.IsDigit(c)) {
       isNumeric = false;
       break;
    }
}
0
source

I prefer the TryParse method. Both of them are approximately equal, I believe that TryParse makes an attempt {} catch {} inside the method, so I doubt that there is a big difference in its execution.

0
source

Source: https://habr.com/ru/post/1703838/


All Articles