int.TryParse = null if not numeric?

Lasse Edsvik picture Lasse Edsvik · Nov 13, 2009 · Viewed 53.8k times · Source

is there some way of return null if it can't parse a string to int?

with:

public .... , string? categoryID) 
{
int.TryParse(categoryID, out categoryID);

getting "cannot convert from 'out string' to 'out int'

what to do?

EDIT:

No longer relevant because of asp.net constraints is the way to solve problem

/M

Answer

Joey picture Joey · Nov 13, 2009

First of all, why are you trying to parse a string to an int and stick the result back into a string?

The method signature is

bool int.TryParse(string, out int)

so you have to give a variable of type int as second argument. This also means that you won't get null if parsing fails, instead the method will simply return false. But you can easily piece that together:

int? TryParse2(string s) {
    int i;
    if (!int.TryParse(s, out i)) {
        return null;
    } else {
        return i;
    }
}