Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to avoid use of Ternary Operator?

User.UserRoleID == 9 ? false : true

Suppose this is my condition and it is now using the ternary operator.
Could someone suggest some other method other than If

like image 855
VVN Avatar asked Apr 05 '17 09:04

VVN


2 Answers

Just turn around the comparison:

bool b = User.UserRoleID != 9;
like image 63
Patrick Hofman Avatar answered Oct 20 '22 21:10

Patrick Hofman


Patrick Hofman's answer is perfect for OP case, since it's very specifically returning true/false. For a more general case, if is the way to go:

User.UserRoleID == 9 ? doOneStuff() : doTheOtherStuff()

it can be easily substituted by the equivalent if/else

if(User.UserRoleID == 9){
   doOneStuff();
}else{
   doTheOtherStuff();
}

In case of assignments and returns, you need to express the left part in both branches:

 int foo = (User.UserRoleID == 9) ? doOneStuff() : doTheOtherStuff()

 if(User.UserRoleID == 9){
       int foo = doOneStuff();
    }else{
       int foo = doTheOtherStuff();
    }

In case of this ternary being a parameter you'll need to explicitely extract it to a variable:

int result = myFunction(User.UserRoleID == 9 ? 4 : 5)

 int parameter;
 if(User.UserRoleID == 9){
       parameter = 4;
    }else{
       parameter = 5;
    }
result = myFunction(parameter);
like image 43
xDaizu Avatar answered Oct 20 '22 20:10

xDaizu