int.TryParse = null if not numeric?

2020-07-03 07:59发布

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

标签: c# .net tryparse
8条回答
Deceive 欺骗
2楼-- · 2020-07-03 08:14

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;
    }
}
查看更多
可以哭但决不认输i
3楼-- · 2020-07-03 08:14

Here's a proper use of Int32.TryParse:

int? value;
int dummy;
if(Int32.TryParse(categoryID, out dummy)) {
    value = dummy;
}
else {
    value = null;
}
return value;
查看更多
贼婆χ
4楼-- · 2020-07-03 08:25

How about this?

public int? ParseToNull(string categoryId)
{
    int id;
    return int.TryParse(categoryId, out id) ? (int?)id : null;
}
查看更多
相关推荐>>
5楼-- · 2020-07-03 08:25

Int is a value type which means there is no such thing as a null int. So no, TryParse will never alter the out parameter so that it is null.

But the problem you're having is you're passing a string to the out parameter of TryParse when its expecting an integer.

You need something like this...

Int categoryID = 0;
string strCategoryID = "somestringmaybeitsaninteger";

int.TryParse(strCategoryID, out categoryID);
查看更多
smile是对你的礼貌
6楼-- · 2020-07-03 08:29

Simplest and one-liner...

int N = int.TryParse(somestring, out N) ? N : 0;

It works 'cause it's evaluated left to right. Null not so easy.

查看更多
甜甜的少女心
7楼-- · 2020-07-03 08:33

TryParse will return false if the string can't be parsed. You can use this fact to return either the parsed value, or null. Anyway I guess that you are intending to return int? from your method, then it would be something like this:

public int? ParseInt(string categoryID) 
{
    int theIntValue;
    bool parseOk = int.TryParse(categoryID, out theIntValue);
    if(parseOk) {
        return theIntValue;
    } else {
        return null;
    }
}
查看更多
登录 后发表回答