Search code examples
c#sqldbnull

DBNull check for ExecuteScalar


The stored procedure for command can return null.Is it correct way to check if the returned value is null or should I also check that obj is null?

object obj = command.ExecuteScalar();
int id = -1;
if (DBNull.Value == obj)
{
   id = Convert.ToInt32(obj );
}

Solution

  • You probably want to change your if-statement to

    if (obj != null && DBNull.Value != obj) { 
        ... 
    }
    

    Right now you're trying to convert if obj == DBNull.Value.