Search code examples
c#stringnull-string

String.IsNullOrEmpty(myString) Vs myString != null


Which one is better among these three?

string myString = ""; 
String.IsNullOrEmpty(myString);

vs

string myString = "";
if(myString.Length > 0 || myString != null)

vs 

string myString = "";
if (m.Length > 0 | m != null)

Former is clearer but is there any performance difference among these? What if, in case a string is never empty, like if taken from a Text Box, which could be empty but not null ?


Solution

  • Well, the version in the question:

    if(myString.Length > 0 || myString != null)
    

    would definitely be worse, as you should test for null first (not second) - ideally short-circuiting on null so you don't attempt to call .Length. But generally I'd just use string.IsNullOrEmpty. You could always write an extension method to make it less verbose if you want (you can call extension methods on null values).

    static bool HasValue(this string s) {
        return !string.IsNullOrEmpty(s);
    }