views:

1783

answers:

4

I have a SQL query which returns only one field - an ID of type INT.

And I have to use it as integer in C# code.

Which way is faster and uses less memory?

int id;
if(Int32.TryParse(command.ExecuteScalar().ToString(), out id))
{
  // use id
}

or

int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
  // use id.Value
}

or

int? id = command.ExecuteScalar() as int?;
if(id.HasValue)
{
  // use id.Value
}
+1  A: 

The latter. Convert.ToInt32() is also an option.

Joel Coehoorn
The first method is from Satan for many reasons. It's slower AND less readable. Yuck.
Dave Markle
Convert.ToInt32() worked for me whereas a cast would not, with command.ExecuteScalar();
JYelton
+2  A: 

The difference between the three performance wise is negligible. The bottleneck is moving the data from the DB to your app, not a trivial cast or method call.

I would go with:

int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
  // use id.Value
}

It fails earlier, if one day people change the command to return a string or a date, at least it will crash and you will have a chance to fix it.

I would also just go with a simple int cast IF I always expected the command to return a single result.

Note, I usually prefer returning an out param than doing the execute scalar, execute scalar feels fragile (the convention that the first column in the first row is a return value does not sit right for me).

Sam Saffron
ExecuteScalar() is a huge win in vb, where you can just do a CInt() or CStr() on it.
Joel Coehoorn
+1  A: 

Use id.HasValue for maximum Nullable Type cool-factor!

frou
+5  A: 

If you expect the command to return null, you should keep in mind that database null (DBNull) is not the same as .NET null. So, conversion of DBNull to int? would fail.

I'd suggest the following:

object result = command.ExecuteScalar();
int? id = (int?)(!Convert.IsDBNull(result) ? result : null);
VladV
Keep in mind that if execute scalar returns no rows, you will get a null. You are correct that if the first row in the first column is null you could be in trouble.
Sam Saffron
but then again it's and ID (I at least read that as identity/key) so DBNull is not an issue
Rune FS
@Sam Saffron, agreed on empty rowset.@Rune FS, we don't know the underlying logic here. I wouldn't assume whether a query might return null or not, based only on a variable name.
VladV
@VladV agreed you should second guess on variable names but I was referring to the fact that it's an ID being returned (says so in the question) and since ID is short of identity and identity in (MS)DB teminology are unique non null values the question is either ambigious or the query will not return DBNulls :)
Rune FS