user5299399
user5299399

Reputation:

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?

Upvotes: 21

Views: 37015

Answers (6)

Conner
Conner

Reputation: 361

if you treat a result of DBNull.Value as the same as null in that they should both be 0, you can use a single line, though you're still using a temporary variable. I won't speak of execution speed:

int countDis = int.TryParse(cmd.ExecuteScalar()?.ToString(), out int temp) ? temp : 0

Upvotes: 1

Nikhil Vartak
Nikhil Vartak

Reputation: 5127

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);

Upvotes: 47

Hamlet Mendez
Hamlet Mendez

Reputation: 163

Because ExecuteScalar can return DBNull, the best way there I found is:

 var result = cmd.ExecuteScalar();
 int countDis = result != null ? Convert.ToInt32(result) : 0;

Upvotes: 2

Moe Sisko
Moe Sisko

Reputation: 12041

I usually use nullable types. e.g. :

string str;

int? countDis = cmd.ExecuteScalar() as int?;
if (countDis == null)
   str = "count is null";
else
   str = "Count is : " + countDis.Value;

This will work for whether ExecuteScalar returns null or DBNull.Value.

Upvotes: 7

M_Idrees
M_Idrees

Reputation: 2172

You can use to get as Object, and check its type then take your decision:

        object obj = cmd.ExecuteScalar();
        if (obj.GetType() == typeof(string))
        {
            //you can do your stuff with STRING
        }
        else if (obj.GetType() == typeof(int))
        {
            //you can do your stuff with INT
        }
        else
        {
            //add here ANYOTHER type you many want in future...
        }

Upvotes: 0

Chandrasekar Kesavan
Chandrasekar Kesavan

Reputation: 795

You can check the scalar value before cast.

var result = cmd.ExecuteScalar();
int countDis =result != null ? int.Parse(result) : 0;

Upvotes: 3

Related Questions