Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing null values to int? [duplicate]

Tags:

c#

null

integer

Since we can not assign null value to integer type variable. So I declared int? type variable and used ternary operator and tried to pass the variable as parameter. But getting error.

int? SAP = 0;

SAP = SAP_num == null ? null :Convert.ToInt32(SAP_num);  // SAP_num is string

While trying to do this I am getting error, type of conditional expression can not be determined because there is no implicit conversion betwen '<null>' and 'int'

Then I tried

int? SAP = 0;
SAP  = Convert.ToInt32(SAP_num);
int confimation_cd = GetCode(SAP);

while trying to do this getting error,cannot convert from 'int?' to 'int' GetCode function accepts integer.

My problem is, if the SAP_num IS NULL , pass as null in the function GetCode else pass as integer value. How to achieve this?

like image 420
nischalinn Avatar asked Feb 09 '23 05:02

nischalinn


1 Answers

SAP = SAP_num == null ? (int?)null :Convert.ToInt32(SAP_num);

Without converting null to int?, the compiler cannot find a common type for the 2 parts of the ternary operator.

BTW it makes your code clearer to use int.Parse rather than Convert.ToInt32, since the former accepts only a string, whereas the latter can accept any fundamental type, even an Int32!

like image 99
wezten Avatar answered Feb 12 '23 09:02

wezten