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 ?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With