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);
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;
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;
}
}
How about this?
public int? ParseToNull(string categoryId)
{
int id;
return int.TryParse(categoryId, out id) ? (int?)id : 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;
}
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;
}
}