Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I merge these two if-statements?

Tags:

c#

I have the following code:

if (a || b)
{
    X();
}

if (a)
{
    Y();
}

Can I somehow merge these two if-statements?

like image 504
magnusarinell Avatar asked Dec 07 '22 23:12

magnusarinell


2 Answers

This would be better, because if first loop exits because a and b are false, then there is no need to check the second loop-

if(a||b)
{
    X();
    if(a)
    {
       Y();
    }
}
like image 123
Shanid Avatar answered Dec 26 '22 14:12

Shanid


If your Y() method always returns true you can write:

if(a || Y() || b) X();

But you need take in account that this code will be read by another person, so it should be easy readable and explain its meaning for the other person. So the best solution depends on meaning of a, b, X and Y. And all of the following will be correct with different semantic meanings:

if(a || b)
{
    X();
    if(a) Y();
}

or

if(a)
{
    X();
    Y();
}
else if(b)
{
    Y();
}
like image 24
Ivan Yuriev Avatar answered Dec 26 '22 13:12

Ivan Yuriev