Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to return null with conditional (?:) operator

Tags:

c#-4.0

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?

like image 496
DenaliHardtail Avatar asked Dec 03 '10 19:12

DenaliHardtail


3 Answers

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

like image 136
Nate Avatar answered Oct 22 '22 10:10

Nate


You need something to coerce the type, like

return id != 0? (int?)Id : null
like image 38
Robert Harvey Avatar answered Oct 22 '22 09:10

Robert Harvey


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

like image 27
Jay Riggs Avatar answered Oct 22 '22 09:10

Jay Riggs