Search code examples
c#.netternary

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.


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