Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to put only one option on a ternary expression?

I am just curious if this is possible or is there a way for this to become a valid syntax for C#:

expression == value ? /*do nothing here, or put some empty block like { ; } */ : SomeClass.SomeMethod();

Edit: For an in-depth discussion and more information, I thought this block would work (if the dictionary key tested does not exist, it adds the dictionary. else, it would skip):

(!packageDict.ContainsKey(desc)) ? packageDict.Add(desc, subtotal) : /*does nothing*/;
like image 868
terrible-coder Avatar asked Mar 18 '16 08:03

terrible-coder


People also ask

How do you use only if condition in ternary operator?

max = (max < b) ? b; In other words, assign value only if the condition is true. If the condition is false, do nothing (no assignment).

How many operands does ternary require?

Remarks. The conditional operator (? :) is a ternary operator (it takes three operands).

Can you do multiple things in a ternary operator?

The JavaScript ternary operator also works to do multiple operations in one statement. It's the same as writing multiple operations in an if else statement.

Can ternary operator have 3 conditions?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


3 Answers

By looking at your code snippet, it simply makes no sense to use a ternary operation here.

All you can do is:

if (!packageDict.ContainsKey(desc))
    packageDict.Add(desc, subtotal)
like image 187
Oliver Avatar answered Nov 15 '22 10:11

Oliver


No, and that makes sense. What would expression be in your no-operation action? null? The same as it was? How should the compiler know that?

This for example will leave the variable unset. What is expression here?

var expression == value ? : SomeClass.SomeMethod();

Just make explicit what you expect, so either this:

expression == value ? null : SomeClass.SomeMethod();

expression == value ? default(Expression) : SomeClass.SomeMethod();

Or this to keep the variable the same when value is true:

expression == value ? expression : SomeClass.SomeMethod();

if (!value) expression = SomeClass.SomeMethod();
like image 38
Patrick Hofman Avatar answered Nov 15 '22 10:11

Patrick Hofman


You should use an IF statement (it is also the most readable option).

An alternative is to use default for your type (e.g. null for reference types or default(value_type) for value types. E.g:

expression == value ? (int?) null : SomeClass.SomeMethod();
like image 37
Alexei - check Codidact Avatar answered Nov 15 '22 10:11

Alexei - check Codidact