4

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?

nischalinn
  • 1,133
  • 2
  • 12
  • 38

2 Answers2

10
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!

wezten
  • 2,126
  • 3
  • 25
  • 48
0

You could create an extension function like this:

public static class StringExt
{
    public static int? ConvertToNullableInt(this string str)
    {
        int temp;

        if (int.TryParse(str, out temp))
            return temp;

        return null;
    }
}

And use it like this:

string SAP_num = null;
int? SAP = SAP_num.ConvertToNullableInt();
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • Please look into my second set of problem. Facing problem when passing the SAP value to the function. `SAP = SAP_num == null ? (int?)null :Convert.ToInt32(SAP_num);` then I tried `int confimation_cd = GetCode(SAP);` `getting error cannot convert from 'int?' to 'int'` – nischalinn Aug 25 '15 at 08:29
  • GetCode probably accepts an int as an input parameter while you are passing a int? – Amir Popovich Aug 25 '15 at 08:34