I observed a strange problem in a piece of code where an adhoc SQL query was not producing the expected output, even though its parameters matched records in the data source. I decided to enter the following test expression into the immediate window:
new SqlParameter("Test", 0).Value
This gave a result of null, which leaves me scratching my head. It seems that the SqlParameter constructor treats zeroes as nulls. The following code produces the correct result:
SqlParameter testParam = new SqlParameter();
testParam.ParameterName = "Test";
testParam.Value = 0;
// subsequent inspection shows that the Value property is still 0
Can anyone explain this behaviour? Is it somehow intentional? If so, it’s potentially rather dangerous…
As stated in the documentation for that constructor:
You simply were calling a different constructor than you thought in your case.
The reason for this is that C# allows an implicit conversion from the integer literal
0to enum types (which are just integral types underneath), and this implicit conversion causes the(string, SqlDbType)constructor to be a better match for overload resolution than the boxing conversion necessary to convertinttoobjectfor the(string, object)constructor.This will never be a problem when you pass an
intvariable, even if the value of that variable is0(because it is not a zero literal), or any other expression that has the typeint. It will also not happen if you explicitly cast theinttoobjectas seen above, because then there is only one matching overload.