RicardoP
RicardoP

Reputation: 207

Using the ternary operator in C# for multiple expressions

By using the ternary operator ?:

perClick  = PlayerPrefs.HasKey("clickpoints") ? PlayerPrefs.GetFloat("clickpoints") : 2.0f;

I want to assign to the "perClick" variable the float stored in the PlayerPref, if the condition evaluates to True, or, if it evaluates to False, I want to set "perClick" to 2. However, if False, I also want to do PlayerPrefs.SetFloat("clickpoints, 2.0f). Is it possible to add more than one statement to the last option?

Upvotes: 0

Views: 802

Answers (1)

AlanK
AlanK

Reputation: 1951

You cannot use the ternary operator to achieve this but you can squeeze the desired effects into one conditional statement:

if (PlayerPrefs.HasKey("clickpoints"))
  perClick = PlayerPrefs.GetFloat("clickpoints");
else
  PlayerPrefs.SetFloat("clickpoints", perClick = 2.0f);

However I cannot stress enough how bad it is to do this, because the logic is obfuscated (easy for even a trained eye to miss important details). Your code should be self documenting where possible, particularly when no extra efficiency can be gained from reducing the number of lines of code (or preferring ?: which is syntactic sugar for if-else most of the time - see Is the conditional operator slow?).

Much better to make your meaning clear...

....
else
{
  perClick = 2.0f;
  PlayerPrefs.SetFloat("clickpoints", perClick);
}

Upvotes: 1

Related Questions