I'd like to do a single line if statement with more than 1 action.
Default is this:
(if) ? then : else userType = (user.Type == 0) ? "Admin" : "User";
But I don't need an "else" only, I need an "else if"
like that in multi line:
if (user.Type == 0) userType = "Admin" else if (user.Type == 1) userType = "User" else if (user.Type == 2) userType = "Employee"
Is there a possibility for that in single line?
One-Line If Statement (Without Else)A single-line if statement just means you're deleting the new line and indentation. You're still writing the same code, with the only twist being that it takes one line instead of two.
In the logical OR ( || ) operator, if one or both of the conditions are true , then the code inside the if statement will execute.
The || operator is like | (§15.22. 2), but evaluates its right-hand operand only if the value of its left-hand operand is false.
Sounds like you really want a Dictionary<int, string>
or possibly a switch
statement...
You can do it with the conditional operator though:
userType = user.Type == 0 ? "Admin" : user.Type == 1 ? "User" : user.Type == 2 ? "Employee" : "The default you didn't specify";
While you could put that in one line, I'd strongly urge you not to.
I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.
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