Search code examples
c#dbnullsqlparameter

Assign null to a SqlParameter


The following code gives an error - "No implicit conversion from DBnull to int."

SqlParameter[] parameters = new SqlParameter[1];    
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex;
parameters[0] = planIndexParameter;

Solution

  • The problem is that the ?: operator cannot determine the return type because you are either returning an int value or a DBNull type value, which are not compatible.

    You can of course cast the instance of AgeIndex to be type object which would satisfy the ?: requirement.

    You can use the ?? null-coalescing operator as follows

    SqlParameter[] parameters = new SqlParameter[1];     
    SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
    planIndexParameter.Value = (object)AgeItem.AgeIndex ?? DBNull.Value;
    parameters[0] = planIndexParameter; 
    

    Here is a quote from the MSDN documentation for the ?: operator that explains the problem

    Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.