Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the ternary operator for multiple operations

Tags:

operators

c#

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?

like image 645
user1240679 Avatar asked Mar 08 '12 11:03

user1240679


2 Answers

Why can't I perform three operations between ? and :

Because these are operands, which are expressions. Each expression evaluates a value; you want multiple statements. From Eric Lippert's blog post about foreach vs ForEach:

The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects.

The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a “statement expression” context.)

You should absolutely write this using an if block. It's clearer.

If you really, really want to use the conditional operator for this, you could write:

// Please, please don't use this.
Func<string> x = () => {
    Properties.Settings.Default.filename = fp;
    Properties.Settings.Default.Save();
    return fp;
};

string filename = fp == null ? Properties.Settings.Default.file : x();
like image 81
Jon Skeet Avatar answered Oct 03 '22 23:10

Jon Skeet


The conditional operator, which is a ternary operator (not a unary operator), is not a replacement for an if statement. It is an operator that returns one of two results. While you can chain this to some extent:

var result = someBool ? "a" : (otherBool ? "b" : "c");

That gets a little hard to read. Further, you're trying to call the Save() function, which does not return a result, hence you cannot use it with this operator.

like image 28
Jon B Avatar answered Oct 03 '22 22:10

Jon B