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 ExecuteScalar returns null, as result of not selecting anything in stored procedure, countDis will have a value of 0. Because Convert.ToInt32(null) = 0.

Update (10/12/2018)

Safer version. Thanks @Moe for highlighting DBNull case.

object result = cmd.ExecuteScalar();
result = (result == DBNull.Value) ? null : result;
int countDis = Convert.ToInt32(result);