string.IsNullOrEmpty() vs string.NotNullOrEmpty()

前端 未结 14 941
遇见更好的自我
遇见更好的自我 2021-02-01 02:56

I\'m curious if any developers use string.IsNullOrEmpty() more often with a negative than with a positive

e.g.

if (!string.IsNullOrEmpty())
相关标签:
14条回答
  • 2021-02-01 03:33

    For those logicians out there, !string.IsNullOrEmpty is not equivalent to string.IsNotNullOrEmpty. @Guffa has it correct. Using DeMorgan's law, it would have to be string.IsNotNullAndNotEmpty to be equivalent.

    ¬(null ∨ empty) ⇔ ¬null ∧ ¬empty

    ¬(null ∨ empty) ≠ ¬null ∨ empty

    The point here, I guess, is that the way it is currently is unambiguous, where as making the opposite unambiguous would be cumbersome.

    0 讨论(0)
  • 2021-02-01 03:33

    That is the most common usage I have seen.

    0 讨论(0)
  • 2021-02-01 03:34

    Personally I prefer to cater for the non negated scenario first. It just makes sense to me to do the true part first and then the false. Comes down to personal style.

    0 讨论(0)
  • 2021-02-01 03:35

    I always create an extension method for "HasContent()" which generally makes sense, follows the "positive" specifications, and saves on code bloat because I use it much more often than its counterpart:

    public static bool HasContent(this string s) {
        return !string.IsNullOrEmpty(s);
    }
    
    0 讨论(0)
  • 2021-02-01 03:37

    Perhaps because then the name would have to be the lengthy IsNotNullAndNotEmpty to be as specific.

    0 讨论(0)
  • 2021-02-01 03:37

    Of course you could always use string.IsNullOrWhiteSpace(string) now instead of string .IsNullOrEmpty(string) from .NET 4.0

    0 讨论(0)
提交回复
热议问题