Question

Is there a way to have the ternary operator do the same as this?:

if (SomeBool)
  SomeStringProperty = SomeValue;

I could do this:

SomeStringProperty = someBool ? SomeValue : SomeStringProperty;

But that would fire the getter and settor for SomeStringProperty even when SomeBool is false (right)? So it would not be the same as the above statement.

I know the solution is to just not use the ternary operator, but I just got to wondering if there is a way to ignore the last part of the expression.

Was it helpful?

Solution

This is as close as you'll get to accomplishing the same as the IF statement, except that u must store the result of the ternary expression; even if u don't really use it...

Full example:

namespace Blah
{
public class TernaryTest
{
public static void Main(string[] args)
{
bool someBool = true;
string someString = string.Empty;
string someValue = "hi";
object result = null;

// if someBool is true, assign someValue to someString,
// otherwise, effectively do nothing.
result = (someBool) ? someString = someValue : null;
} // end method Main
} // end class TernaryTest
} // end namespace Blah 

OTHER TIPS

That makes no sense.

The ternary operator is an expression.
An expression must always have a value, unless the expression is used as a statement (which the ternary operator cannot be).

You can't write SomeProperty = nothing

I think you're looking for something like a short-circuit evaluation (http://en.wikipedia.org/wiki/Short-circuit_evaluation) with the C# ternary operator.

I believe you'll find that the answer is NO.

In contrast to whoever downvoted it, I think it is a valid question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top