Jul 14, 2008

C# SqlParameter strange behaviour (or not so strange?)

I had strange experience with the SqlCommand.AddWithValue method.
Consider the following code:

SqlCommand cmd = new SqlCommand();
cmd.CommandText =
"SELECT * FROM Products WHERE ProductID=@ProductID "+
cmd.Parameters.AddWithValue(
"@ProductID", 12);

Can you spot error?
It is a developer error ;). The problem is the "+" after the command text line.
What is strange is that it won't generate compiler error. Instead this, the text will become:

"SELECT * FROM Products WHERE ProductID=@ProductID @ProductID"

(the name of the variable added will be appended to the command text)
Offcourse in the normal case you will not have + between the CommandText = and Parameters.AddWithValue, but if
you accidently miss this tiny error
it will be pretty hard to spot it later (as the compiler will not complain).


Be careful ;)

No comments: