Reputation:
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
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
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
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
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
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
Reputation: 795
You can check the scalar value before cast.
var result = cmd.ExecuteScalar();
int countDis =result != null ? int.Parse(result) : 0;
Upvotes: 3