Am refactoring some old code and see something in the following format:
Type = rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"
which should not work if rec["IsFlagged"] is null, in which case I need to return null. How would one refactor to keep code in one line, if possible?
I can do something like but am wondering if the following can be achieved in one line to have minimal changes to code
if (rec["IsFlagged"] != null)
{
return rec["IsFlagged"].ToString() == "True" ? "Yes" : "No"
}
else
{
return null
}
Thanks,
The original code works fine.
rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"
The ? operator before .ToString()
prevents the method from being called if null. The result of rec["IsFlagged"]?.ToString()
would be null
Then, it compares null
to "True"
which is false (they are not equal).
The ternary operator then evaluates "No"
and assigns it to the lvalue.
EDIT So, now you want 3 possible results: "Yes", "No" or null. A single ternary only gives you two choices. There are many possibilities and yours is fine, unless you have multiple places doing something similar. In that case, you could use an extension method:
public String CheckTrue(this object input) {
return input?.ToString() == "True" ? "Yes" : "No"
}
and then in your specific case:
return rec["IsFlagged"]?.CheckTrue()
Another alternative is to use multiple ternary operators?
return rec["IsFlagged"]==null ? null : (rec["IsFlagged"].ToString() == "True" ? "Yes" : "No");