Petkov Alexander
Petkov Alexander

Reputation: 65

?: ternary operator with two declarations after

Can I use a ternary operator when I have more than one operation to perform per case?

var replace = list[row][col + 1] == "P" ? list[row][col] = "P", list[row][col] 
= "P" : list[row][col + 1] = ".";

Upvotes: 0

Views: 36

Answers (1)

John Wu
John Wu

Reputation: 52260

The way to write this code is:

if (list[row][col + 1] == "P")
{
    //multiple operations
}
else
{
    //multiple operations
}

The ternary operator is not mean to support operations. It supports choosing between two values. You really shouldn't be assigning anything after the ? mark.

As it turns out the = operator not only assigns but also returns a value, so you might figure out some way to make it work that way, for example by initializing an array with several values that are the result of an assignment:

// If c is true, a will be set to "A" and b will b e set to "B"
var q = c ? new[]{ a = "A", b="B"} : new string[]{};

But this is not the way the ?: operator is meant to be used and would be very confusing code.

Upvotes: 1

Related Questions