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
I think your best option is to do what your boss says, this one isn't worth it! That said, add a few spaces around yours and I like it better.
int someValue = int.Parse(value ?? "0");
In this case the earlier is more readable as its a trivial example. **However in your case they are not equivalent, as the ?? isn't the same as string.IsNullOrEmpty **
The latter would be better in cases where the if was complex. I'd say horses for courses. Just depends on the audience. Try and keep it simple.
public int doSomeWork(string value)
{
return int.Parse(value ?? "0");
}
public int doSomeWork(string value)
{
if(value == null)
value = "0";
int SomeValue = int.Parse(value);
return SomeValue;
}
the two options are not equivalent. A part from a bug in the second snippet (it should read if(string.IsNullOrEmpty(value))
, it will handle two cases, null and empty strings, whereas the ??
operator only handles nulls.
A part from that it's way more readable. I side with your boss.
I definitely prefer the null coalesce operator (??) over a series of if statements. Especially when you need to coalesce more than one value, the operator approach is FAR more readable. This plays into other newer features of C#, such as lambda expressions, LINQ sugar syntax, etc. The less code there is to muddy up the actual intentful code, the clearer the intent should/will be.
Personally I'd go for the corrected version of your bosses - possibly with even more checks on it - if the string's empty, yours will, as you say throw an exception, as "" isn't a well formatted number and ?? only checks for null.
Something like:
public int doSomeWork(string value) {
int someValue = 0;
if (!string.IsNullOrEmpty(value)) {
Int.TryParse(value, out someValue);
}
}
Which resolves the issue where value equals "Forty Two".
Your first snippet will only check if value == null
, but the seconds snippet checks if value == string.Empty || value == null
. I don't know what the requirements of your method is but those two snippets will do different things.