SqlParameter contructor compiler overload choice

Posted by Ash on Stack Overflow See other posts from Stack Overflow or by Ash
Published on 2010-06-11T04:36:30Z Indexed on 2010/06/11 4:42 UTC
Read the original article Hit count: 305

Filed under:
|
|

When creating a SqlParameter (.NET3.5) or OdbcParameter I often use the SqlParameter(string parameterName, Object value) constructor overload to set the value in one statement.

When I tried passing a literal 0 as the value paramter I was initially caught by the C# compiler choosing the (string, OdbcType) overload instead of (string, Object).

MSDN actually warns about this gotcha in the remarks section, but the explanation confuses me.

Why does the C# compiler decide that a literal 0 parameter should be converted to OdbcType rather than Object? The warning also says to use Convert.ToInt32(0) to force the Object overload to be used.

It confusingly says that this converts the 0 to an "Object type". But isn't 0 already an "Object type"? The Types of Literal Values section of this page seems to say literals are always typed and so inherit from System.Object.

This behavior doesn't seem very intuitive given my current understanding? Is this something to do with Contra-variance or Co-variance maybe?

© Stack Overflow or respective owner

Related posts about c#

Related posts about ADO.NET