views:

814

answers:

3

When I retrieve any Scalar value from the database, I usually write code like this for nullable fields.

cmd.ExecuteScalar() == DBNull.Value ? 0 : (int)cmd.ExecuteScalar()

But I don't like it because it executes the Executescalar statement twice. It's an extra trip to the server for my website and in favor of performance I don't want to do this.

Is there any way I can get rid of this extra ExecuteScalar()?

+8  A: 

Just use a variable to cache the result:

var o = cmd.ExecuteScalar();
return o == DBNull.Value ? 0 : (int)o;
Matt Hamilton
+3  A: 
 object o = cmd.ExecuteScalar();
 return (o== DBNull.Value) ? 0 : (int)o;
Charles Bretana
I prefer this over "var." I think the use of "var" is, as I expected, being abused. Although, I do realize that some people, Jon Skeet for example, believe it is more readable, which I don't understand.
BobbyShaftoe
Really? You care what type "o" is in that code? It's getting discarded on the very next line. As a reader of the code, the use of "object" vs "var" is just noise to me.
Matt Hamilton
+7  A: 

Write yourself an extension method for the sql command.

public static T ExecuteNullableScalar<T>(this SqlCommand cmd)
    where T : struct
{
    var result = cmd.ExecuteScalar();
    if (result == DBNull.Value) return default(T);
    return (T)result;
}

Usage becomes:

int value = cmd.ExecuteNullableScalar<int>();
askheaves
setting up T : struct does not allow one to use strings. I removed the inheritance.
Cyril Gupta