Avoiding Multiple Ifs In C # - Best Practice

Scenario: Let's say we need to check the address lines. which includes address line1, address line2, city, country, zip code If any of the properties is entered, all other fields are required. If none of them are entered, the check should not be started.

To achieve this, I got two lines of the If statement. how

if(AddressLine1 != null || AddressLine2 != null || Town != null || Country != null) { if(AddressLine1 != null && AddressLine2 != null && Town != null && Country != null) == false { return false; } } 

Note. I am using C #. Are there any language constructs that I can use.

+4
source share
4 answers

Well, a null coalescing operator can help with the first:

 if (AddressLine1 ?? AddressLine2 ?? Town ?? Country != null) { if (AddressLine1 == null || AddressLine2 == null || Town == null || Country == null) { return false; } // Presumably there more here } 

You might want to write some helper methods:

 if (IsAnyNonNull(AddressLine1, AddressLine2, Town, Country)) { if (IsAnyNull(AddressLine1, AddressLine2, Town, Country)) { return false; } } 

If the utility methods look something like this:

 public static bool IsAnyNonNull(params object[] values) { return values.Any(x => x != null); } public static bool IsAnyNull(params object[] values) { return values.Any(x => x == null); } 

Of course, you still have two if , but I think that this is basically necessary here.

+6
source
 private bool IsAddressValid(params string[] addressParts) { return addressParts.Any(p => p != null) ? addressParts.All(p => p != null) : true; } 

Called like this:

 var addressValid = IsAddressValid(AddressLine1, AddressLine2, Town, County); 
+8
source

If you create an array of fields in a group, you can do:

 var fields = new object[] {AddressLine1, AddressLine2, Town, Country}; return fields.All(f => f == null) || fields.All(f => f != null); 
+6
source

Define this:

 public static bool SameNullness(params object[] values) { int nullCount = 0; foreach (var value in values) { if (value == null) nullCount++; } return nullCount == values.Length; } 

Then use it like:

 SameNullness(AddressLine1, AddressLine2, Town, Country); 
0
source

All Articles