I have a method that will receive a string
, but before I can work with it, I have to convert it to int
. Sometimes it can be null
and I ha
Actually you could refactor to
var value = 0;
int.TryParse(yourString, out value);
either way you always have a valid integer (if that is the goal)
You can do it your way? Cool!
If is definitely more readable, unless everyone is more of a C# wonk than me.
[Assuming you only need to check for null, and not empty string also, as others have pointed out]
The semantic difference between the two is that ??
is an expression, while if
is a statement. An expression says "perform a calculation and return a result", exactly the semantics you seek. More work has to be done to allow an if
statement to express the same semantics; beyond that, the if
leaves room for more logic than the calculation, room you don't need.
You should use the ??
operator because it expresses exactly the desired intent.
Why parse the string "0" just to get integer value 0? I definitely prefer this:
public int doSomeWork(string value) {
int someValue;
if (String.IsNullOrEmpty(value)) {
someValue = 0;
} else {
someValue = Int32.Parse(value);
}
}
Why not just use TryParse()
?
public int doSomeWork(string stringValue)
{
int value;
int.TryParse(stringValue, out value);
return value;
}
The above code will return 0
if the value is anything but an actual number.
So in my opinion, my example is the most readable. I try to parse the int and return it. No coalesce operator, and no string methods are used. This method also handles the exceptions that might be thrown when parsing (unless you WANT the exceptions...).
Another solution is
int someValue = string.IsNullOrEmpty(value) ? 0 : int.Parse(value);