Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check multiple boolean conditions in C# if statements

I have 3 booleans on my code (C#) and an int32 property that depends on what booleans are true and false. Whats the best way to accomplish this in another way than if statements like:

if(a && b && !c)
   d = 1;
if(a && !b && !c)
   d = 2;
//etc.. ect...

EDIT: The 3 booleans must have every combination possible to set the int32 value.

EDIT 2: The value of "d" can be the same for two different boolean comparations.

like image 313
Phoenix_uy Avatar asked Apr 09 '13 14:04

Phoenix_uy


3 Answers

You could use a Karnaugh map to reduce your equations and have fewer ifs.

https://en.wikipedia.org/wiki/Karnaugh_map

like image 183
SamFisher83 Avatar answered Nov 16 '22 23:11

SamFisher83


It is better to capture the intent of the operation instead of explicitly check the boolean values.

For example:

public void Check()
{
   if (HasOrdered())
   {
      // do logic
   }
}

private bool HasOrdered()
{
    return a && !b && !c;
}

private bool HasBooked()
{
    return a && b && !c;
}
like image 32
Davin Tryon Avatar answered Nov 17 '22 00:11

Davin Tryon


I think what your doing now is perfectly fine and any other solutions would be down to preference.

My preference, where it applies would be to separate the checks out if possible.

 if (!a)
    return;
 if (!b)
    return;
 if (!c)
    return;

This would be useful in the event that you need to check certain prereqs before issuing a function, like if the user has logged in, if a parameter exists and is in the right context, along with other items.

Like i said this might not apply but i just wanted to voice my opinion

like image 2
PsyKzz Avatar answered Nov 16 '22 23:11

PsyKzz