confused by C# type conversion

I'm new to C# but familiar with vb.net

my setVendor functions expects an int and a string

why does this work

shopify.setVendor(System.Convert.ToInt32(reader["ProductID"]), System.Convert.ToString(reader["Vendor"]));

but this fails for both parameters:

shopify.setVendor(int.Parse(reader["ProductID"]), reader["Vendor"].ToString);

very confused. It wants a string and I give it a string but it doesn't accept it . . . error converting string to int

Jon Skeet
people
quotationmark

There's an overload of Convert.ToInt32 which accepts object. There's no such overload for int.Parse. The argument must be a string at compile time. You would need:

shopify.setVendor(int.Parse(reader["ProductID"].ToString()),
                  reader["Vendor"].ToString());

(Note the change from ToString to ToString() for the second argument... previously you were specifying the ToString method group which is used to create delegates; with the change you're calling ToString instead.)

Or:

// This only works if the value *is* a string
shopify.setVendor(int.Parse((string) reader["ProductID"]),
                  reader["Vendor"].ToString());

Ideally, however, you'd get back the values in the correct forms already, so you could use:

shopify.setVendor((int) reader["ProductID"], (string) reader["Vendor"]);

Or:

// Set up productIdColumn and vendorColumn first
shopify.setVendor(reader.GetInt32(productIdColumn), reader.GetString(vendorColumn));

Also note that setVendor is not a conventional .NET method name.

people

See more on this question at Stackoverflow