1

Given this question shorthand If Statements: C#

What is wrong with this?

    int userID;
    Int32.TryParse(request.userID, out userID);

    userID > 0 ? user = DuoUser.LoadUser(userID): ;

It gives the error:

only assignment call increment decrement and new object expressions can be used as a statement

As far as I can see it should work, but something is wrong?

EDIT:

I have also tried:

    int userID = 0;

    userID > 0 ? user = DuoUser.LoadUser(userID): null;

But it still gives the same error.

Community
  • 1
  • 1
Alex
  • 3,730
  • 9
  • 43
  • 94
  • You've to assign the value to something, like: `user = userID > 0 ? DuoUser.LoadUser(userID): ;` The statement is like `variable - if - then - else` – Christoph K Jan 22 '16 at 10:30

3 Answers3

6

Change the last line to:

user = userID > 0 ? DuoUser.LoadUser(userID) : null ;

The error message is correct. You must assign the result of the ternary operator to something.

UPDATE

Your edit to the question still has the same problem. You are not assigning the result of the ternary expression to anything, you are attempting to assign within the statement.

The ternary operator simply says

something = condition ? result if condition is true : otherwise this result if false.

You could alternatively do this:

if (userID > 0)
    user = DuoUser.LoadUser(userID);

which some may find easier to read in any event.

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
  • Do you not mean `user = userID > 0 ? DuoUser.LoadUser(userID) : null;`? – Luke Joshua Park Jan 22 '16 at 10:30
  • Yes - I spotted that and already correctd it. My edit and your comment must have arrived at about the same time. – Colin Mackay Jan 22 '16 at 10:31
  • BTW: is there a common opinion about the ternary operator in terms of clean code, code readability and code refactor? – Falco Alexander Jan 22 '16 at 10:47
  • 1
    @FalcoAlexander Way back when I was learning C++ (20+ years ago) the consensus seemed to be simply "don't use them". I think some people still feel that way, but I will use them when it aids readability. Sometimes the `if` construct just seems too bulky, whereas the ternary operation makes more sense if the expression is simple and can fit one line without horizontal scrolling. – Colin Mackay Jan 22 '16 at 13:36
1

You can try this:

userID= userID > 0 ? DuoUser.LoadUser(userID): null;
Max
  • 1,810
  • 3
  • 26
  • 37
tunir
  • 11
  • 1
1

The ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison. This can be accomplished with if-statements or other constructs.

So your code becomes

    int userID;
    Int32.TryParse(request.userID, out userID);
    userID = userID > 0 ? user = DuoUser.LoadUser(userID): 0;
mck
  • 978
  • 3
  • 14
  • 38