3

Given the following line of code:

cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayID);

I receive the following error: The SqlParameterCollection only accepts non-null SqlParameter type objects, not String objects.

However, rewriting it to use object intialization:

cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar) { Value = customer.DisplayID });

works just fine. Any pointer on why this is occuring?

Pete Maroun
  • 2,045
  • 2
  • 18
  • 27

2 Answers2

2

The problem is a misplaced closing parenthesis:

cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar)).Value = customer.DisplayId;

Note that there are 2 closing parentheses before .Value. As you originally entered it, you are doing cmd.Parameters.Add(...); where the ... is

new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId

and that evaluates to customer.DisplayId, hence the message about it not accepting string types.

Also, you can add the parameter more succinctly with

cmd.Parameters.AddWithValue("@displayId", customer.DisplayId);

As to why new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId returns customer.DisplayId, consider that the assignment operator returns the value being assigned as its result, and in this case that would be customer.DisplayId. This is why you can assign a value to several variables at once:

int i, j, k;
i = j = k = 42;
Jeff Ogata
  • 56,645
  • 19
  • 114
  • 127
2
cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayID);

is the same as

var customerDisplayId = customer.DisplayID;
new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customerDisplayId;
cmd.Parameters.Add(customerDisplayId);

now do you see why the compiler is complaining?

Bala R
  • 107,317
  • 23
  • 199
  • 210