Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with SqlParameter constructor vs object initializer

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?

like image 965
Pete Maroun Avatar asked Jun 08 '26 15:06

Pete Maroun


1 Answers

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;
like image 94
Jeff Ogata Avatar answered Jun 11 '26 03:06

Jeff Ogata