How can I use the ternary ? : condition to perform multiple operations, if expression is true/false?
wbsource = (exp) ? (Do one thing) : (Do second thing)
wbsource = (exp) ? (Do one thing) (Do second thing) : (Do second thing)
For eg:
Why can’t I perform three operations between ? and :
filename = (fp!=null) ? fp; Properties.Settings.Default.filename=fp; Properties.Settings.Default.Save; : Properties.Settings.Default.file;
With simple if condition, I would have written in a simple way like:
if(fp!null)
{
filename = fp;
Properties.Settings.Default.filename;
Properties.Settings.Default.Save();
}
else
{
filename = Properties.Settings.Default.file
}
What’s a sweet short way to write using the above ternary operator?
Because these are operands, which are expressions. Each expression evaluates a value; you want multiple statements. From Eric Lippert’s blog post about
foreachvsForEach:You should absolutely write this using an
ifblock. It’s clearer.If you really, really want to use the conditional operator for this, you could write: