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

后端 未结 7 2219
既然无缘
既然无缘 2020-12-18 20:14

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?

相关标签:
7条回答
  • 2020-12-18 20:48

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

    0 讨论(0)
提交回复
热议问题