One liner for If string is not null or empty else

后端 未结 6 1455
孤城傲影
孤城傲影 2020-12-08 18:03

I usually use something like this for various reasons throughout an application:

if (String.IsNullOrEmpty(strFoo))
{
     FooTextBox.Text = \"0\";
}
else
{
          


        
相关标签:
6条回答
  • 2020-12-08 18:41

    You can write your own Extension method for type String :-

     public static string NonBlankValueOf(this string source)
     {
        return (string.IsNullOrEmpty(source)) ? "0" : source;
     }
    

    Now you can use it like with any string type

    FooTextBox.Text = strFoo.NonBlankValueOf();
    
    0 讨论(0)
  • 2020-12-08 18:44

    This may help:

    public string NonBlankValueOf(string strTestString)
    {
        return String.IsNullOrEmpty(strTestString)? "0": strTestString;
    }
    
    0 讨论(0)
  • 2020-12-08 18:48

    There is a null coalescing operator (??), but it would not handle empty strings.

    If you were only interested in dealing with null strings, you would use it like

    string output = somePossiblyNullString ?? "0";
    

    For your need specifically, there is the conditional operator bool expr ? true_value : false_value that you can use to simplify if/else statement blocks that set or return a value.

    string output = string.IsNullOrEmpty(someString) ? "0" : someString;
    
    0 讨论(0)
  • 2020-12-08 18:48

    Old question, but thought I'd add this to help out,

    #if DOTNET35
    bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
    #else
    bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
    #endif
    
    0 讨论(0)
  • 2020-12-08 18:55

    You could use the ternary operator:

    return string.IsNullOrEmpty(strTestString) ? "0" : strTestString
    
    FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
    
    0 讨论(0)
  • 2020-12-08 19:01

    You can achieve this with pattern matching with the switch expression in C#8/9

    FooTextBox.Text = strFoo switch
    {
        { Length: >0 } s => s, // If the length of the string is greater than 0 
        _ => "0" // Anything else
    };
    
    0 讨论(0)
提交回复
热议问题