Cast to int on SqlCommand-ExecuteScalar error handling
I have code that is possibly fragile. This statement here
int countDis = (int)cmd.ExecuteScalar();
If I change the stored procedure to not return ANYTHING, then that casting to
(int) is going to blow up. If I simply remove it, then I cannot compile.
What is the best code practice for defensive coding in this situation?
Just change the code as:
int countDis = Convert.ToInt32(cmd.ExecuteScalar());
This will ensure that even if
null, as result of not selecting anything in stored procedure,
countDis will have a value of
Convert.ToInt32(null) = 0.
Safer version. Thanks @Moe for highlighting
object result = cmd.ExecuteScalar(); result = (result == DBNull.Value) ? null : result; int countDis = Convert.ToInt32(result);