Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ternary operator: "only assignment, call, increment..."

Tags:

c#

.net

I have action dictionary defined as:

var actions = new Dictionary<string, Action<string, string>>();

I put there actions like:

actions.Add("default", (value, key) => result.Compare(value, properties[key], Comparers.SomeComparer, key));
...

I'm using this code to run it:

if (actions.ContainsKey(pair.Key))
{
    actions[pair.Key](pair.Value, pair.Key);
}
else
{
    actions[""](pair.Value, pair.Key);
}

It works just fine, but I wanted to use '?' notation to make it shorter:

actions.ContainsKey(pair.Key) ? actions[pair.Key](pair.Value, pair.Key) : actions[""](pair.Value, pair.Key);

This code shows me error:

Error 1 Only assignment, call, increment, decrement, and new object expressions can be used as a statement

actions[pair.Key](pair.Value, pair.Key) isn't it a call? Am I missing something? Is it possible to use '?' notation with action dictionaries? I was trying to find something about that but it's hard to find anything about '?' operator and this error because '?' is ignored by google.

like image 719
Kamil Budziewski Avatar asked Aug 20 '13 06:08

Kamil Budziewski


People also ask

Can we use assignment operator in ternary operator?

both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.

Can ternary operator be used without assignment?

Nope you cannot do that.

Is it good practice to use ternary operator?

The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear.

Why use ternary operator instead of if else?

The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .


2 Answers

Try this instead:

actions[actions.ContainsKey(pair.Key) ? pair.key : ""](pair.Value, pair.Key);

This will fix your issue.

like image 189
Kundan Singh Chouhan Avatar answered Sep 22 '22 03:09

Kundan Singh Chouhan


The ?: Conditional operator is defined as:

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression

Your actions don't return a value, so what is the return value of ?: meant to be?

like image 36
Damien_The_Unbeliever Avatar answered Sep 20 '22 03:09

Damien_The_Unbeliever