-4

Is there a way to use ? : notation in c# without assigning result of the expression, or even with expressions, after ? operator, which do not return any values.

E.g. I want to run something like it

(1=1) ? errorProvider.SetError(control,"Message") : DoNothing();

expression? DoSomething (): DoSomethingElese()

where DoSomething and DoSomethingElse returns types are void.

Darren
  • 68,902
  • 24
  • 138
  • 144
Darqer
  • 2,847
  • 9
  • 45
  • 65

4 Answers4

4

No.

?: returns a value based upon a boolean condition. You can't use void in the expression.

Just use if

   if (expression) {
        DoSomething();
   } else {
        DoSomethingElse();
   }

http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.110).aspx

Darren
  • 68,902
  • 24
  • 138
  • 144
3

No. The whole point of the ternary operator is that it returns something. In other words: the expression must have a return type (other than void). In this case, you just need to use an if/else construction.

Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
2

Closest you can get is by extending the boolean type:

public static void IIF(this bool condition, Action doWhenTrue, Action doWhenFalse)
{
    if (condition)
        doWhenTrue();
    else
        doWhenFalse();
}

Then you win a oneliner:

(1 == 1).IIF(() => DoSomething(), () => DoSomethingElse());
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
1

As others have said, you can't - an If/Else would be the right choice. In your example though, you could do something like:

errorProvider.SetError(control, SomeCondition ? "Message" : string.Empty) 
NDJ
  • 5,189
  • 1
  • 18
  • 27