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条回答
对你真心纯属浪费
2楼-- · 2019-01-31 16:33

Try this:

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();

You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:

this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();

But this example only works since a possible value for this.approved_by is the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.

查看更多
爷、活的狠高调
3楼-- · 2019-01-31 16:33

You can also do it in your query, for instance in sql server, google ISNULL and CASE built-in functions.

查看更多
▲ chillily
4楼-- · 2019-01-31 16:45

My guess is the best you can come up with is

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
                                                      : planRec.approved_by.ToString();

Of course since you're hinting at the fact that approved_by is an object (which cannot equal ""), this would be rewritten as

this.approved_by = (planRec.approved_by ?? string.Empty).ToString();
查看更多
迷人小祖宗
5楼-- · 2019-01-31 16:47

You are looking for the C# coalesce operator: ??. This operator takes a left and right argument. If the left hand side of the operator is null or a nullable with no value it will return the right argument. Otherwise it will return the left.

var x = somePossiblyNullValue ?? valueIfNull;
查看更多
别忘想泡老子
6楼-- · 2019-01-31 16:52

I use extention method SelfChk

static class MyExt {
//Self Check 
 public static void SC(this string you,ref string me)
    {
        me = me ?? you;
    }
}

Then use like

string a = null;
"A".SC(ref a);
查看更多
放我归山
7楼-- · 2019-01-31 16:54

With C#6 there is a slightly shorter way for the case where planRec.approved_by is not a string:

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