string.IsNullOrEmpty() vs string.NotNullOrEmpty()

前端 未结 14 947
遇见更好的自我
遇见更好的自我 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条回答
  •  梦毁少年i
    2021-02-01 03:51

    I would actually be inclined to offer a different answer from the "it's ambiguous" explanation provided by several others (though I agree with that answer as well):

    Personally, I like to minimize nesting in my code, as (to me) the more curly braces code has, the harder it becomes to follow.

    Therefore I'd much prefer this (for example):

    public bool DoSomethingWithString(string s) {
        if (string.IsNullOrEmpty(s))
            return false;
    
        // here's the important code, not nested
    }
    

    to this:

    public bool DoSomethingWithString(string s) {
        if (!string.IsNullOrEmpty(s)) {
            // here's the important code, nested
        } else {
            return false;
        }
    }
    

    This is a pretty specific scenario (where a null/empty string prompts an immediate exit) and clearly isn't the way a method using IsNullOrEmpty would always be structured; but I think it's actually pretty common.

提交回复
热议问题