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*/;
max = (max < b) ? b; In other words, assign value only if the condition is true. If the condition is false, do nothing (no assignment).
Remarks. The conditional operator (? :) is a ternary operator (it takes three operands).
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.
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.
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)
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();
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();
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