Is it best to write If statement in a block or single line?

Veteran C# (Unity) here. I had sometime saw if statement written as

(conditions) ? main outcome : alternative outcome; (forgot the name for this so I will call it A)

in oppose to the common

if (aslkdf)
{
dfsdfsd;
} and this here B

So my questions are:

  1. is A better Then B or is just a preference?
  2. is there a situation where A would be better then B and vice versa?
    Thanks,

As far as I’m aware, as long as you are not copying an array with a thousand values the speed will be the same between the two, so there’s no real difference performance wise.

The Ternary Operator (A) often falls into the “Syntactic Sugar” category, implying that makes your code more readable, so yes, it’s a matter of preference but also no because it’s good practice.

As to where to use it, that’s something I never thought of, I just use it, got used to it because it saves me so many lines, but here’s an example of a simple method that handles how pause behaves in a game I’m working on that uses the operator twice:

public void PauseGame()
{
    paused = !paused;
    Time.timeScale = paused ? 0 : 1;
    state.SetState = paused ? GameState.NotPlaying : GameState.Playing;
    pauseMenu.SetActive(paused);
}

I suppose I use it when I need and else statement.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.