0

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.

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • What if you replaced `SomeStringProperty = ` with `Console.WriteLine(`? – SLaks Dec 05 '11 at 17:14
  • 2
    That's like asking "can I divide by using the subtraction operator?" –  Dec 05 '11 at 17:17
  • The ternary operator is not the issue. The issue is that you want to suppress the *assignment* operation, which is unrelated to the ternary operator. And the way to suppress the assignment operation is to um not execute an assignment. – Raymond Chen Dec 05 '11 at 22:54

3 Answers3

5

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

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @HenkHolterman: I don't mean `Nothing` as a keyword; I mean _nothing_ as in not changing the value. – SLaks Dec 05 '11 at 17:51
  • 1
    I know, `SomeProperty = ;` might have been clearer. But C# does have [void expressions](http://stackoverflow.com/a/2030141/60761). So an expression does not always have to have a value. But in `?:` they do have to. – H H Dec 05 '11 at 20:24
2

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 
Kevin Carrasco
  • 1,042
  • 7
  • 9
1

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.

Cyberherbalist
  • 12,061
  • 17
  • 83
  • 121