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?
The problem is a misplaced closing parenthesis:
Note that there are 2 closing parentheses before
.Value. As you originally entered it, you are doingcmd.Parameters.Add(...);where the...isnew SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayIdand that evaluates to
customer.DisplayId, hence the message about it not acceptingstringtypes.Also, you can add the parameter more succinctly with
As to why
new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayIdreturnscustomer.DisplayId, consider that the assignment operator returns the value being assigned as its result, and in this case that would becustomer.DisplayId. This is why you can assign a value to several variables at once: