Assignment using Ternary Operator

Couple of days back, I happened to come across a question in StackOverflow. Question seemed pretty straightforward, but at the same time, interesting. How would one use ternary operator for assignment. For example, how would write following code using ternary operator.

var a = 1;
var b = 2;
var c = 3;
var flag = false;
if(flag)
a = c;
else
b = c;

Obviously, following wouldn’t work.

// CS0131 The left-hand side of an assignment must be a variable, property or indexer
(flag?a:b) = c;

One way to use ternary operator would using Action.

(flag ? new Action(() => a = c): () => b = c)();

But that doesn’t quite give you the clean syntax of Ternary Operator. That brings us to the second way using features exposed by C# 7.2. Let us rewrite the code.

(flag ? ref a : ref b) = c;

Enjoy coding…

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s