0

The following error comes with ternary operator.

Error: Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'int'

Why is this error appearing even though I have specified (int)(result) for the ExecuteScalar result? How can we correct it?

CODE

    public int? GetWINFromAssociateID(int associateID)
    {
        int? WIN =null;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string commandText = DataLayerConstants.GetWINFromAssociateIDCommand;
            using (SqlCommand command = new SqlCommand(commandText, connection))
            {
                command.CommandType = System.Data.CommandType.Text;
                command.Parameters.AddWithValue("@payroll_svc_assoc_id", associateID);

                var result = command.ExecuteScalar();
                WIN = result == DBNull.Value ? null : (int)(result);
            }
        }
        return WIN;
    }

UPDATED REFERENCES

  1. Conditional operator cannot cast implicitly?
  2. Type inference woes, part one - by Eric Lippert
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 1
    Read this answer and the links you'll find there: http://stackoverflow.com/a/2452375/385844 – phoog Feb 09 '13 at 07:41

2 Answers2

3

You should cast your null in ternary operator to int?:

Win=result==DBNull.Value?(int?)null:(int?)result;
Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38
  • 2
    It's not necessary to cast both null and result; casting either one is sufficient. – phoog Feb 09 '13 at 07:38
  • 1
    In this case it is necessary due to result has type object. – Kirill Bestemyanov Feb 09 '13 at 09:25
  • Ok, I was reading too hastily; my comment was only half correct. I should have written "It's not necessary to cast both `null` and `result`; casting `result` is sufficient" (because there is an implicit conversion from null to `int?`). – phoog Feb 11 '13 at 16:13
0

It is because there Command.ExecuteScalar returns an instance of object type; and you may not be returning an integer.

You need to use int.Parse or better int.TryParse;

int.Parse(result.ToString());

OR

int temp = -1;
int.TryParse(result.ToString(), out temp);
daryal
  • 14,643
  • 4
  • 38
  • 54