AustinWBryan
AustinWBryan

Reputation: 3326

How to return multiple values from a single ternary operator?

Let's say I have the following code:

int x    = GetBoolValue() ? 0 : 1;
string y = GetBoolValue() ? "foo" : "bar";
float z  = GetBoolValue() ? 0.4f : 0.5f;

Is there anyway to condense these three statements into one, to make the code simpler to read?

Upvotes: 0

Views: 2095

Answers (1)

AustinWBryan
AustinWBryan

Reputation: 3326

Using C# 7 value tuples, you can do something like this:

var (x, y, z) = GetBoolValue() ? (0, "foo", 0.4f) : (1, "bar", 0.5f);

The var can be removed if they've already been declared and this will still work fine.

Upvotes: 7

Related Questions