2

This could be a trivial question, I've seen several different variations of Cast.

  • What is the difference?
  • Is one better than another (Performance)?
  • Is it just a matter of preference, code legibility?

Example One:

command.ExecuteScalar() as string;

Example Two:

(string)command.ExecuteScalar();

Both will impact the ExecuteScalar() differently, so the question is when interacting with the database is one more ideal than another?

Greg
  • 11,302
  • 2
  • 48
  • 79
  • 1
    `as` will fail gracefully. – Brad Aug 20 '14 at 20:57
  • 2
    @kirinthos `[displayText](linkUrl)`. Also how did you manage to comment, you have under 50 rep. Did the flagging dialogue make that? – gunr2171 Aug 20 '14 at 20:58
  • i can finally comment, it auto-converted my answer to a comment, which i then couldn't edit/delete, because i couldn't do comment stuff – kirinthos Aug 21 '14 at 14:10

2 Answers2

7

The first ( command.ExecuteScalar() as string; )will do a runtime attempt to convert the result of ExecuteScalar() into a string. If the resulting type is not a string, you will receive null. The as keyword also only performs reference conversions, nullable conversions, and boxing conversions, so you can't use it directly with non nullable value types.

The second ( (string)command.ExecuteScalar(); ) will do a conversion to string directly, and raise an InvalidCastException if the resulting value is not a string.

Is one better than another (Performance)?

In general, using the second option should provide (insignificantly) better performance if you know the result is always going to be a string.

Is it just a matter of preference, code legibility?

This is where I make the stronger differentiation. Using as suggests that the result may not be a string, and you will be handling the null check. Using a direct cast suggests that you know it's always a string, and anything else is an error and should raise an exception.

In my opinion, this should be the deciding factor for which to choose, since it shows your intent directly in the code.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
4

(string)command.ExecuteScalar() will throw an exception if command.ExecuteScalar() cannot be cast.

command.ExecuteScalar() as string will just return null instead.

Jeff
  • 12,555
  • 5
  • 33
  • 60