Update:
When a database returns a value through the scalar, it will always be an object
. So when the value is returned you should have a preconceived notion of what the type will be. Why would you use ToString();
when you you have a SELECT
which passes two parameters.
As if it doesn't exist it will always throw a null
. So in my refactor I believed the as
would be the proper approach. As ToString()
will throw an error --- So what form of cast
is it comparable to?
I've got some code I'm maintaining, but in apart of my refactor I came across a ToString()
attached to an ExecuteScalar
. My question would be, does the usage of ToString()
equate to:
(string)command.ExecuteScalar();
Or would it represent this:
command.ExecuteScalar() as string;
Obviously the as string
would fail gracefully, where the cast (string)
would actually fall into an InvalidCastException
. So when you call:
command.ExecuteScalar().ToString();
Which method of casting
is it attempting to do?
No, it doesn't mean either of those - it simply means calling ToString()
on whatever the value is.
In particular, if the value is not a string, it will convert it to a string anyway - whereas string
would fail with InvalidCastException
and the as
would return null.
So for example:
object x = 10;
string a = x.ToString(); // "10"
string b = x as string; // null
string c = (string) x; // Bang
Of course, ToString()
can still throw an exception too - most obviously if the target of the call is a null
reference.
Personally, I would suggest using a cast if you know what the result type should be - although the result of ExecuteScalar
is more commonly a numeric value (e.g. a count) rather than a string.
Yes, that means an exception will be thrown if you're wrong - but if your query isn't doing what it's meant to anyway, then stopping due to an exception may well be better than going ahead with a bogus view of the world. (See my blog post on casting vs as
for more on this attitude.)
See more on this question at Stackoverflow