5

I've got a method that whose return type is a nullable int.

 private int? LookupId(string name, string stateAbbreviation)

I'm trying to cleanup the code and decided to use a conditional operator on the return statement.

return id != 0 ? id : null;

Basically, if the id is not 0, go a head and return the id. It should never return 0 from the db. If, by chance, it is 0, return null.

The error is "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '' "

The conditional op is intended to replace a functioning If...Else statement.

Is there anything wrong with trying to use a conditional this way, in this combination? What am I missing?

2
  • Make sure id is an int?, and not an int. Dec 3, 2010 at 19:09
  • You are comparing the variable id with 0 and return another variable named Id (capital I). Is this intentional?
    – Bazzz
    Dec 3, 2010 at 19:10

4 Answers 4

12

Try return id != 0 ? Id : (int?)null; ?

1
  • 3
    Funny enough, return id != 0 ? (int?)Id : null; also works. Dec 3, 2010 at 19:10
4

You need something to coerce the type, like

return id != 0? (int?)Id : null
2

Is id of type int? (and not int)?

1

Check this

   private int? getme()
    {
        int? id;
        id= 0;
        return id != 0 ? id : null;
    }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.