Search code examples
c#stringnull

Checking several string for null in an if statement


Is there a better (nicer) way to write this if statement?

if(string1 == null && string2 == null && string3 == null && string4 == null && string5 == null && string6 == null){...}

Solution

  • Perhaps using the null-coalescing operator(??):

    if((string1 ?? string2 ?? string3 ?? string4 ?? string5 ?? string6) == null){ ;}
    

    If all strings are in a collection you can use Linq:

    bool allNull = strings.All(s => s == null);