Shortest way to check for null and assign another

2019-01-31 16:06发布

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?

10条回答
小情绪 Triste *
2楼-- · 2019-01-31 16:56

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:

public static void CallIfNonEmpty(string value, Action<string> action)
{
    if (!string.IsNullOrEmpty(value))
        action(value);
}

And then just use it:

CallIfNonEmpty(this.approved_by, (s) => planRec.approved_by = s);
查看更多
走好不送
3楼-- · 2019-01-31 16:58

Use the C# coalesce operator: ??

// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YournullValue;
查看更多
混吃等死
4楼-- · 2019-01-31 16:59

The coalesce operator (??) is what you want, I believe.

查看更多
唯我独甜
5楼-- · 2019-01-31 16:59

To extend @Dave's answer...if planRec.approved_by is already a string

this.approved_by = planRec.approved_by ?? "";
查看更多
登录 后发表回答