Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking several string for null in an if statement

Tags:

string

c#

null

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

if(string1 == null && string2 == null && string3 == null && string4 == null && string5 == null && string6 == null){...}
like image 732
Dušan Avatar asked Feb 20 '13 14:02

Dušan


People also ask

How do you compare NULL values in if condition?

Use an "if" statement to create a condition for the null. You can use the boolean value as a condition for what the statement does next. For example, if the value is null, then print text "object is null". If "==" does not find the variable to be null, then it will skip the condition or can take a different path.

Does Isnull check for empty string?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

What happens if string in is null?

Example using a null check Very often in programming, a String is assigned null to represent that it is completely free and will be used for a specific purpose in the program. If you perform any operation or call a method on a null String, it throws the java. lang. NullPointerException.


2 Answers

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);
like image 71
Tim Schmelter Avatar answered Sep 28 '22 13:09

Tim Schmelter


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)
{...}
like image 15
juharr Avatar answered Sep 28 '22 15:09

juharr