Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int32.TryParse() or (int?)command.ExecuteScalar()

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
}
like image 567
abatishchev Avatar asked Jul 23 '09 22:07

abatishchev


People also ask

What is ExecuteScalar ()?

ExecuteScalar: Use this operation to execute any arbitrary SQL statements in SQL Server to return a single value. This operation returns the value only in the first column of the first row in the result set returned by the SQL statement.

What is Int32 TryParse string Int32?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

Does TryParse throw exception?

Parse() method throws an exception if it cannot parse the value, whereas TryParse() method returns a bool indicating whether it succeeded. However, TryParse does not return the value, it returns a status code to indicate whether the parse succeeded and does not throw exception.

What does int TryParse return?

The Int32. TryParse() method returns a boolean value as return and provides the converted value as an out parameter.


1 Answers

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

like image 199
Sam Saffron Avatar answered Oct 02 '22 16:10

Sam Saffron