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.
both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.
Nope you cannot do that.
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.
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 .
Try this instead:
actions[actions.ContainsKey(pair.Key) ? pair.key : ""](pair.Value, pair.Key);
This will fix your issue.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With