Is there any way to avoid using the ternary operator?

User.UserRoleID == 9 ? false : true

Suppose this is my condition, and now it uses the ternary operator.
Can anyone suggest a different method than If

+6
source share
4 answers

Just rotate the comparison:

bool b = User.UserRoleID != 9;
+45
source

Patrick Hofman's answer is ideal for the OP case, as it returns true / false very accurately. For a more general case , if this is the way to go :

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

it is easy to replace it with equivalent if / else

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

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

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

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

, , :

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

 int parameter;
 if(User.UserRoleID == 9){
       parameter = 4;
    }else{
       parameter = 5;
    }
result = myFunction(parameter);
+2

, . ; - , (¿?), .

return (User.UserRoleID == 9) ? false : true

switch(User.UserRoleID == 9){
    case true:
        return true;
    case false:
        return false;
    default:
        //return... wait, what?
        throw new Exception("Boolean math broken. Please, restart the universe");
 }

:

return (User.UserRoleID == 9) ? doOneThing(): doTheOtherThing();

switch(User.UserRoleID == 9){
    case true:
        return doOneThing();
    case false:
        return doTheOtherThing();
}

. , :

try {
    bool result = User.UserRoleID == 9;
    throw new Activator.CreateInstance(result.ToString() + "Exception");
} catch (TrueException e){
    return doOneThing();
}catch(FalseException e){
    return doTheOtherThing();
}

: , . , , (, , ), .

0

How easy is it to use literals or User.UserRoleID == 9instead ? Not ideal if this repeats itself throughout the code, but if you need it only once or twice ...truefalse

0
source

Source: https://habr.com/ru/post/1016315/


All Articles