Cannot return null with conditional (? :) operator

I have a method for which the return type is an int with a null value.

 private int? LookupId(string name, string stateAbbreviation)

I am trying to clear the code and decided to use a conditional statement in the return statement.

return id != 0 ? id : null;

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

Error: "The type of the conditional expression cannot be determined because there is no implicit conversion between" int "and" "

The conditional op is intended to replace the current If ... Else statement.

Is there something wrong trying to use a conditional expression this way in this combination? What am I missing?

+3
source share
4 answers

id int? ( int)?

+2

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

+4

You need something to force a type like

return id != 0? (int?)Id : null
+3
source

check this

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

Source: https://habr.com/ru/post/1778386/


All Articles