Vaccano
Vaccano

Reputation: 82467

Is there a way to not return a value from last part of a ternary operator

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.

Upvotes: 0

Views: 137

Answers (3)

SLaks
SLaks

Reputation: 887887

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

Upvotes: 5

Cyberherbalist
Cyberherbalist

Reputation: 12329

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.

Upvotes: 1

Kevin Carrasco
Kevin Carrasco

Reputation: 1052

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 

Upvotes: 2

Related Questions