40

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

if(string1 == null && string2 == null && string3 == null && string4 == null && string5 == null && string6 == null){...}
5
  • 1
    if(String.IsNullOrWhiteSpace(string1)&& ... -> so you don't only check for null Strings, but also for empty and some containing only spaces Commented Feb 20, 2013 at 14:42
  • 3
    Do you really need so many separate string variables? Can you not make an array or list of strings and use that instead? It will most likely simplify a lot of other operations as well. Commented Feb 20, 2013 at 14:43
  • 1
    With the information you've given, no, not really (I guess you can break it over several lines if that helps you), but @JohnWillemse point stands. If you need that many string variables, maybe you need to think about using some different data structure that can encapsulate this logic. Commented Feb 20, 2013 at 14:44
  • Personally I'd just write it exactly like that. Although I don't think I'd ever have that many strings to test for nullness without them being in some kind of collection. Commented Feb 20, 2013 at 14:59
  • Thank you all for your answers. Using list is a good idea, but I also like Tim's solution with null-coalescing operator, so I accepted his answer. Commented Feb 21, 2013 at 11:31

8 Answers 8

65

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);
Sign up to request clarification or add additional context in comments.

Comments

15

You could put all the strings in a list and use

if(listOfStrings.All(s=>s==null))

At the very least you can put it on multiple lines

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

2 Comments

i used || instead of && to overcome in between null value
@stom What you you mean by "in between null value"? If you use || instead of && you'll just get at least one value is null instead of all values are null.
13

If you made a function like this:

public static bool AllNull(params string[] strings)
{
    return strings.All(s => s == null);
}

Then you could call it like this:

if (AllNull(string1, string2, string3, string4, string5, string6))
{
    // ...
}

Actually, you could change AllNull() to work with any reference type, like this:

public static bool AllNull(params object[] objects)
{
    return objects.All(s => s == null);
}

2024 Update for .NET 9/ C# 13:

Now we have both nullable annotation and params collection, so we can write AllNull() like so:

public static bool AllNull(params Span<object?> objects)
{
    foreach (var obj in objects)
    {
        if (obj is not null)
            return false;
    }

    return true;
}

This has the advantage that you can call it passing a list of reference objects without the compiler having to allocate an array and pass it to the AllNull() method, which could be a lot more efficient.

You can also implement it using IEnumerable<object?>:

public static bool AllNull(params IEnumerable<object?> objects)
{
    return objects.All(s => s == null);
}

This allows even more collection types to be passed to it (but it will usually not allow the same level of optimisation as using Span<object?>.)

3 Comments

Nice and clean solution!! Though similar to @Tim Schmelter solution, made it way easy by separating it in function and providing a complete example.
Great answer. I would just suggest to use nullable objects array (params object?[] objects)
@MatiasMasso Updated for C# 13 (ten years later ;))
6
string[] strs = new string[] { string1, string2, string3 };
if(strs.All(str => string.IsNullOrEmpty(str))
{
  //Do Stuff
}

Or use strs.All(str => str == null) if you don't want to check for empty strings.

Comments

3

Make a IEnumerable of strings (list or array....), then you can use .All()

var myStrings = new List<string>{string1,string2,string3....};
if(myStrings.All(s => s == null))
{
   //Do something
}

3 Comments

Or in a single line ... if (Enumerable.All(new string[] {str1, str2, str3, str4}, s => s == null))
@JimMischel: This creates an additional collection just to shorten an evaluation. Btw, it does not even really shorten it.
@TimSchmelter: Yes, it does create an additional collection, as does the answer that you upvoted.
2

Well, I don't know if it is nicer or better, or not, you can use IEnumerable.Any method like this;

Determines whether a sequence contains any elements.

List<string> list = new List<string>{"string1","string2","string3", "string4", "string5"};
if(list.Any(n => n == null))
{

}

And you can use Enumerable.All() method like;

Determines whether all elements of a sequence satisfy a condition.

if (Enumerable.All(new string[] { string1, string2, string3, string4, string5 }, s => s == null) )
{
       Console.WriteLine("Null");
}

Comments

2

In case you want to check null or empty, here is another way without arrays:

if (string.Concat(string1, string2, string3, string4, string5).Length == 0)
{
    //all null or empty!
}

1 Comment

Does not check if all are null, the same as with Dennisch's answer.
0

This should do the same:

if (string.IsNullOrEmpty(string1 + string2 + string3 + string4 + string5 + string6)){...}

2 Comments

This will return True if they are empty as well not just null.
Just use string.IsNullOrWhiteSpace to solve the aforementioned problem and its cake. Love that approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.