How To Cast ExecuteScalar Return Value

SqlCommand.ExecuteScalar(). I believe many of you use this handy method quite often.
But it is what it returns causing the trouble. This method returns an object.

If you try to cast that with (Type), this will almost always return you an invalid cast exception.
It is okay to use (Int32) or (string). But for (double), it needs to be done in another way.
Always use Convert.ToInt32() and Convert.ToDouble() for these situation.
This will save you a day.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s