views:

188

answers:

2

Hi,

I have just finished converted a vb.net app to c# and one of the lines is to get @ReturnValue from the parameter.

I ended up having to CAST a lot of things..

Is there not a easier way

here is what i have

int rc = ((System.Data.SqlTypes.SqlInt32)(((System.Data.SqlClient.SqlParameter)(cmd.Parameters["@ReturnValue"])).SqlValue)).Value;

In vb.net it was as simple as doing this

Dim rc As Integer = Convert.ToInt32(cmd.Parameters("@ReturnValue").Value)

Alot easier :-)

But the problem with C# is the property Value isn't available unless I Cast to SqlParameter and i also need to cast to Sqltypes.SqlInt32 - i can't just do a standard Convert.ToInt32

+1  A: 

It's just as easy to do it in C#:

int rc = (int) cmd.Parameters("@ReturnValue").Value;
Keltex
The OP wrote: "the problem with C# is the property Value isn't available unless I cast ..."
tanascius
+2  A: 

This isn't a C# versus VB.NET thing - it's about the types you're using to declare your variables. If cmd is an IDbCommand, you're in for a lot of casting.

The IDbCommand.Parameters property returns an IDataParametersCollection, which contains a collection of Object instances. Since Object doesn't have a property called Value, you need to cast each instance to SqlParameter before accessing Value.

SqlCommand.Parameters, by contrast is a SqlParameterCollection, which contains a collection of SqlParameter instances. If you declare your cmd variable as a SqlCommand, you can access its parameters' values in the straightforward way to which you're accustomed. (At the cost of being tightly coupled to the implementations in the SqlClient namespace.)

Jeff Sternal
Thanks, yes I was using the interface....
mark smith