Shortest way to check for null and assign another value if not

前端 未结 11 2164
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 01:32

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 doi

相关标签:
11条回答
  • 2020-12-13 01:50

    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();
    
    0 讨论(0)
  • 2020-12-13 01:50

    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);
    
    0 讨论(0)
  • 2020-12-13 01:52

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

    this.approved_by = planRec.approved_by ?? "";
    
    0 讨论(0)
  • 2020-12-13 01:53

    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);
    
    0 讨论(0)
  • 2020-12-13 01:58

    Starting with C# 8.0, you can use the ??= operator to replace the code of the form

    if (variable is null)
    {
        variable = expression;
    }
    

    with the following code:

    variable ??= expression;
    

    More information is here

    0 讨论(0)
  • 2020-12-13 02:00

    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;
    
    0 讨论(0)
提交回复
热议问题