Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Multiple If's in c# - Best practise

Scenario: Lets say we got to check for address lines. which includes addressline1, addressline2,Town,Country,Postcode If any one of the property is entered, all other fields are mandatory. If none of it is entered, the validation doesnt have to get trigged.

To achieve it, I ended up with two lines of If statement. Like

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 i can make use of.

like image 326
Hunter Avatar asked Nov 30 '22 09:11

Hunter


1 Answers

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

To be called like so:

var addressValid = IsAddressValid(AddressLine1, AddressLine2, Town, County);
like image 53
Dave D Avatar answered Dec 05 '22 04:12

Dave D