Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to check which part of an if statement is correct [closed]

i wonder how can you check which part of a if statement was the correct one. For example if you have this :

int a = 1, b, c, d;
    if(a > 0 || b > 1 || c > 2 || d > 3)
    {
        //do stuff
    }

Now in this case the one that made the if correct is a. So how can you verify this ? Basically you can put them in 4 different if's but if you have to do a repetitive code for each one you can probably come up with some method for it but isn't there actually a way to pass some value for example ?

like image 658
kopelence Avatar asked Jan 08 '16 20:01

kopelence


1 Answers

One approach in situations when you need to know not only the overall result, but also the item that made the result true, is to put conditionals into an array, and perform the chain of ORs ||s yourself:

var conditions = new[] {a > 0, b > 1, c > 2, d > 3};
var whichOne = Array.IndexOf(conditions, true);
if (whichOne >= 0) {
    Console.WriteLine("Condition number {0} is true", whichOne);
} else {
    Console.WriteLine("The condition is false");
}

Note that this approach is different from the || chain in that it does not short circuit the evaluation. In other words, all four conditions would be evaluated before the call to IndexOf.

like image 141
Sergey Kalinichenko Avatar answered Sep 26 '22 14:09

Sergey Kalinichenko