'How to make a conditional statement with two parameter do not consists of repetitive statements without using external function in C#?
Let there be two boolean variables a
and b
, and each combination of the truth values of both causes a particular different procedure. Check this code:
if(a)
{
// Block A
if(b)
{
// statement 1
}
else
{
// statement 2
}
}
else {
// Block B
if(b)
{
// statement 3
}
else
{
// statement 4
}
}
Is there any way to make it to be not repetitive without making a separate function? (What I mean by repetitive is block A and block B have the same conditional but different statement)
Solution 1:[1]
Would the switch expression work for you?
(a, b) switch {
(true, true) => ...,
(true, false) => ...`,
(false, true) => ...,
(false, false) => ...,
};
Solution 2:[2]
You could avoid nesting if
s like so
if(a && b)
{
// statement 1
}
else if(a && !b)
{
// statement 2
}
else if(!a && b)
{
// statement 3
}
else
{
// statement 4
}
I'm not sure you would consider it more succint, but I at least find it more readable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Arthur Rey |