First, a bit of background. Read the question and accepted answer posted here for a specific scenario for my question. I'm not sure if other, similar cases exist but this is the only case I am aware of.
The above "quirk" is something that I've been aware of for a long time. I didn't understand the full breadth of the cause until just recently.
Microsoft's documentation on the SqlParameter
class sheds a little more light on the situation.
When you specify an Object
in the value parameter, the SqlDbType
is
inferred from the Microsoft .NET Framework type of the Object.
Use caution when you use this overload of the SqlParameter
constructor
to specify integer parameter values. Because this overload takes a
value of type Object
, you must convert the integral value to an Object
type when the value is zero, as the following C# example demonstrates.
Parameter = new SqlParameter("@pname", Convert.ToInt32(0));
If you do
not perform this conversion, the compiler assumes that you are trying
to call the SqlParameter (string, SqlDbType) constructor overload.
(emph. added)
My question is why does the compiler assume that when you specify a hard coded "0" (and only the value "0") that you are trying to specify an enumeration type, rather than an integer type? In this case, it assumes that you are declaring SqlDbType
value, instead of the value 0.
This is non-intuitive and, to make matters worse, the error is inconsistent. I have old applications that I've written which have called stored procedures for years. I'll make a change to the application (often times not even associated with my SQL Server classes), publish an update, and this issue will all of a sudden break the application.
Why is the compiler confused by the value 0, when an object containing multiple method signatures contain two, similar signatures where one parameter is an object/integer and the other accepts an enumeration?
As I've mentioned, I've never seen this as a problem with any other constructor or method on any other class. Is this unique to the SqlParameter
class or is this a bug inherit within C#/.Net?
See Question&Answers more detail:
os