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

I have 3 booleans for my code (C #) and an int32 property, which depends on which booleans are true and false . What is the best way to do this in a different way than if statements like:

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

EDIT: 3 logic gates must have any combination to set the value to int32.

EDIT 2: The value of "d" may be the same for two different Boolean comparisons.

+8
c # if-statement boolean
source share
5 answers

It is better to fix the intention of the operation, rather than explicitly checking the logical values.

For example:

 public void Check() { if (HasOrdered()) { // do logic } } private bool HasOrdered() { return a && !b && !c; } private bool HasBooked() { return a && b && !c; } 
+25
source share

You can use the Carnot map to reduce your equations and have fewer ifs.

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

+9
source share

You can do the search table hint given by @Adriano if you have a lookup_table filled with values ​​for the index [0..8):

 var index = new [] { a,b,c }.Aggregate(0, (a,i) => return 2*a + (i?1:0)); int d = lookup_table[index]; 

Change EDIT question made this inappropriate: What does d mean?

If this is the number of false values ​​(possibly from the sample code), do this

 int d = new [] { a,b,c }.Count(b => !b); 

Strike>

+2
source share

I think that your affairs are now fine, and any other decisions will not be preferred.

My preference, in which it is applied, would be, if possible, to separate the checks.

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

This would be useful if you need to check certain preconditions before releasing the function, for example, if the user is logged in, if the parameter exists and is in the correct context along with other elements.

As I said, this may not apply, but I just wanted to voice my opinion

+2
source share

I don’t see anything wrong with how you do it, but if the result is the same for several conditions, you can simplify it by creating a truth table and simplifying the conditions.

For example, if d should be 0 at any time a false, you can simplify:

 if(a) if(b && !c) d = 1; if(!b && !c) d = 2; ... else d = 0; 

Or, if there is some mathematical pattern (for example, a , b and c represent three digits of a binary number), you can perform bit arithmetic.

If, however, you have 8 different results (one for each combination of a , b and c ), then your method will be fine.

0
source share

All Articles