Easier way of writing null or empty?

前端 未结 5 370
失恋的感觉
失恋的感觉 2020-11-29 12:22

I\'m sure I\'ve missed something here. With a certain project I need to check if a string is empty or null.

Is there an easier way of writing this?

i         


        
相关标签:
5条回答
  • // if the string is not defined to null then IsNullOrEmpty it works great but if string is defined null then trim will throw exception.

    if(string.IsNullOrEmpty(myString.Trim()){
     ...
    }
    

    //you can use IsNullOrWhiteSpace which work well for multiple white space in string .i.e it return true for multiple white space also

     if(string.IsNullOrWhiteSpace (myString.Trim()){
         ...
        }
    
    0 讨论(0)
  • 2020-11-29 12:38

    Yes, there's the String.IsNullOrEmpty helper method for exactly this already:

    if (String.IsNullOrEmpty(myString)) {
        ...
    }
    
    0 讨论(0)
  • 2020-11-29 12:43

    To avoid null checks you can use ?? operator.

    var result = value ?? "";
    

    I often use it as guards to avoid sending in data that I don't want in methods.

    JoinStrings(value1 ?? "", value2 ?? "")
    

    It can also be used to avoid unwanted formatting.

    string ToString()
    {
        return "[" + (value1 ?? 0.0) + ", " + (value2 ?? 0.0) + "]";
    }
    

    This can also be used in if statements, it's not so nice but can be handy sometimes.

    if (value ?? "" != "") // Not the best example.
    {
    }
    
    0 讨论(0)
  • 2020-11-29 12:44
    if (string.IsNullOrEmpty(myString)) {
      ...
    }
    

    Or you could take advantage of a quirk in extension methods, they allow this to be null:

    static class Extensions {
        public static bool IsEmpty(this string s) {
            return string.IsNullOrEmpty(s);
        }
    }
    

    which then lets you write:

    if (myString.IsEmpty()) {
      ...
    }
    

    Although you probably should pick another name than 'empty'.

    0 讨论(0)
  • 2020-11-29 12:47

    If you are on .NET 4, you can use

    if(string.IsNullOrWhiteSpace(myString)){
    
    }
    

    else:

    if(string.IsNullOrEmpty(myString)){
    
    }
    
    0 讨论(0)
提交回复
热议问题