0

The following compiles ok:

if (_logon.LogonToConnector())
{
    MessageBox.Show("Logon Success");
}
else
{
    MessageBox.Show("Logon Failed");
}

But for the more concise equivalent:

_logon.LogonToConnector() ? MessageBox.Show("Logon Success") : MessageBox.Show("Logon Failure");

The compiler gives the error:

Only assignment, call, increment, decrement, and new object expressions can be used as a statement UniformTestClient

Where did I go wrong?

Rob Bowman
  • 7,632
  • 22
  • 93
  • 200
  • 1
    The ternary operator is used to return values and those values must be assigned. Here is a workaround https://stackoverflow.com/a/38451083/2946329 – Salah Akbari Jul 18 '18 at 08:55
  • 5
    _Where did I go wrong?..._ `Only assignment, call, increment, decrement, and new object expressions can be used as a statement UniformTestClient` Its all about that – B001ᛦ Jul 18 '18 at 08:55
  • 1
    Just a single google-search and you would have got the answer far faster then typing in your question. – MakePeaceGreatAgain Jul 18 '18 at 09:00

2 Answers2

6

Put it

MessageBox.Show(_logon.LogonToConnector() 
  ? "Logon Success"
  : "Logon Failed");

since ternary operator must return a value.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

Ternary operator returns a value based on true/false which has to be assigned. You can't shorten your if/else statement this way.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

You could do something like

string message = _logon.LogonToConnector() ? "Logon Success" : "Logon failed";

MessageBox.Show(message);
Bukk94
  • 419
  • 1
  • 6
  • 23