Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line if statement with 2 actions

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?

like image 759
Nagelfar Avatar asked Sep 18 '12 20:09

Nagelfar


People also ask

How do you write an if statement in one 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.

Can you use || in an if statement?

In the logical OR ( || ) operator, if one or both of the conditions are true , then the code inside the if statement will execute.

What is || in if condition?

The || operator is like | (§15.22. 2), but evaluates its right-hand operand only if the value of its left-hand operand is false.


1 Answers

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.

like image 75
Jon Skeet Avatar answered Oct 20 '22 15:10

Jon Skeet