views:

46

answers:

2

I have a method that either adds or updates a record in a DB (SQL Server), and it returns the RecordID as an (Int32) Output Parameter, and a success/failure result as (Int32) Return Value.

Given that I'm specifying the type of these parameters, why do I have to cast them when they are returned?

I expected to used the following:

enquiryID = cmd.Parameters["@EnquiryID"].Value;

...but I and up having to jump through a couple of extra hoops:

enquiryID = Int32.Parse(cmd.Parameters["@EnquiryID"].Value.ToString());

It's not the end of the world, but it just seems like a longwinded solution. Why does Parameters.Value return an SqlParameters.Value object rather than an Int32?

UPDATE:

OK, I'm convinced - direct casting FTW: (int)cmd.Parameters["@EnquiryID"].Value

+2  A: 

SQL Server does not specify the type of data it is returning, so C# has no way to infer the type before processing it. Also, SqlParamater is generalized, so that it passes and object to and from SQL Server. SQL Server is performing the cast on its end.

Also, instead of using Int32.Parse(cmd.Parameters["@EnquiryID"].Value.ToString()), if you know its always going to be an int, you could just do a direct cast (int)cmd.Parameters["@EnquiryID"].Value. If the value might be returned as a null, you could then add

object value = cmd.Parameters["@EnquiryID"].Value;
if(!value.Equals(DBNull.Value)
    enquiryID = (int)value;
phsr
This might end up being preferable to a bunch of if statements`int value = value.Equals(DBNull.Value) ? null : (int)value` Instead of null you can put a default value as well
Chris T
Re: sql server performing cast - Yes, this makes sense. FYI, the value will never be null but the issue (and your example) is worth noting. Thanks
CJM
@Chris T: I always forget the ? operator, since I rarely use it, thanks!
phsr
+2  A: 

The Value property of a SqlParameter object is typed as object, which means that it can return any given type.

Your way of returning the actual value is wrong, you should never convert to string in order to parse an int32. What is in the Value propery is just a boxed version of your value, therefore this should suffice:

enquiryID = (int)cmd.Parameters["@EnquiryID"].Value;
Jamiec
My way isn't really 'wrong' as such - it works, after all, but yes the direct casting method is much better. Thanks
CJM