int.TryParse = null if not numeric?

那年仲夏 提交于 2019-12-04 00:05:59

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;
    }
}

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;

How about this?

public int? ParseToNull(string categoryId)
{
    int id;
    return int.TryParse(categoryId, out id) ? (int?)id : null;
}
user5000501

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.

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;
    }
}

Do you want to do something like this?

public int? Parse(string categoryID) 
{
  int value;
  if (int.TryParse(categoryID, out value))
  {
    return value;
  }
  else
  {
    return null;
  }
}

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);

** this answer was down-voted a lot ** Although it is a possible solution - it is a bad one performance wise, and probably not a good programming choice.

I will not delete it, as I guess many programmers might not be aware of this, so here is an example how not to do things:

use try and catch

try
{
res = Int32.Parse(strVAR)
}
catch(exception ex) 
{
 return null;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!