I am pulling varchar
values out of a DB and want to set the string
I am assigning them to as "" if they are null
. I'm currently doing it like this:
if (string.IsNullOrEmpty(planRec.approved_by) == true)
this.approved_by = "";
else
this.approved_by = planRec.approved_by.toString();
There seems like there should be a way to do this in a single line something like:
this.approved_by = "" || planRec.approved_by.toString();
However I can't find an optimal way to do this. Is there a better way or is what I have the best way to do it?
To assign a non-empty variable without repeating the actual variable name (and without assigning anything if variable is null!), you can use a little helper method with a
Action
parameter:And then just use it:
Use the C# coalesce operator: ??
The coalesce operator (??) is what you want, I believe.
To extend @Dave's answer...if planRec.approved_by is already a string