18

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?

Community
  • 1
  • 1
RLH
  • 15,230
  • 22
  • 98
  • 182
  • 1
    Not directly related to your question, but I think a better advice would be to use a named parameter (`new SqlParameter("@pname", value: 0)`) instead of `Convert.ToInt32()`. – svick Jan 09 '13 at 18:18
  • Why don't people always specify the dbtype and length? Not doing it causes hard to detect problems and ruins the plan cache. Is it just to save a few keystrokes or is there some other benefit? – adrianm Jan 09 '13 at 19:33
  • @adrianm, it's because a constructor exists that takes a parameter name and a value. Why have the constructor on the SqlParameter class if you can't use it? This isn't about saving keystrokes, it's about using a constructor on a class on their being a pseudo-collision between two constructors because one accepts an object, where another accepts an enumeration. If this is "poor coding practice", the constructor that takes a value shouldn't exist in the first place. – RLH Jan 09 '13 at 19:47
  • Instead of the unnecessary method call in `new SqlParameter("@pname", Convert.ToInt32(0))` it is better to resolve the issue by specifying the desired type directly with cast syntax, as in `new SqlParameter("@pname", (object)0)`. This is the usual thing to do when overload resolution picks the wrong overload (or refuses to pick any overload). In general, if stuff like `M(a, b, c, d)` will not work, insert precise types where needed, for example `M((T1)a, b, (T2)c, d)`. – Jeppe Stig Nielsen Jun 08 '17 at 17:39

5 Answers5

19

It's because a zero-integer is implicitly convertible to an enum:

enum SqlDbType
{
    Zero = 0,
    One = 1
}

class TestClass
{
    public TestClass(string s, object o)
    { System.Console.WriteLine("{0} => TestClass(object)", s); } 

    public TestClass(string s, SqlDbType e)
    { System.Console.WriteLine("{0} => TestClass(Enum SqlDbType)", s); }
}

// This is perfectly valid:
SqlDbType valid = 0;
// Whilst this is not:
SqlDbType ohNoYouDont = 1;

var a1 = new TestClass("0", 0);
// 0 => TestClass(Enum SqlDbType)
var a2 = new TestClass("1", 1); 
// => 1 => TestClass(object)

(Adapted from Visual C# 2008 Breaking Changes - change 12)

When the compiler performs the overload resolution 0 is an Applicable function member for both the SqlDbType and the object constructors because:

an implicit conversion (Section 6.1) exists from the type of the argument to the type of the corresponding parameter

(Both SqlDbType x = 0 and object x = 0 are valid)

The SqlDbType parameter is better than the object parameter because of the better conversion rules:

  • If T1 and T2 are the same type, neither conversion is better.
    • object and SqlDbType are not the same type
  • If S is T1, C1 is the better conversion.
    • 0 is not an object
  • If S is T2, C2 is the better conversion.
    • 0 is not a SqlDbType
  • If an implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists, C1 is the better conversion.
    • No implicit conversion from object to SqlDbType exists
  • If an implicit conversion from T2 to T1 exists, and no implicit conversion from T1 to T2 exists, C2 is the better conversion.
    • An implicit conversion from SqlDbType to object exists, so the SqlDbType is the better conversion

Note that what exactly constitutes a constant 0 has (quite subtly) changed in Visual C# 2008 (Microsoft's implementation of the C# spec) as @Eric explains in his answer.

RichardTowers
  • 4,682
  • 1
  • 26
  • 43
  • Wow, thank you for your thoroughness. This certainly clarifies the situation. Now that it's been explained, I guess I have to agree that this makes sense and this method is a better way of interpreting the 0. Still, this is quite confusing behavior to the more casual developer. – RLH Jan 09 '13 at 12:43
  • Could it be that the last time you compiled you used `Visual C# 2005` and this time you used `2008` and you've been bitten by the breaking changes they made? Otherwise sounds like a standard case of bit rot. – RichardTowers Jan 09 '13 at 12:59
  • I deleted my question, because I'm beginning to wonder if that has been any part of the problem. The last, previous time I compiled this application was in 2011, so I was using VS 2010. I always update my projects to the latest VS version, but not the .Net runtime variant, when a new version of VS comes out. I don't know, but I'm going to have to accept that this one is a complete mystery. – RLH Jan 09 '13 at 13:02
  • 1
    Very thorough answer! Nice job going to the specification. – Eric Lippert Jan 09 '13 at 14:55
18

RichardTowers' answer is excellent, but I thought I'd add a bit to it.

As the other answers have pointed out, the reason for the behaviour is (1) zero is convertible to any enum, and obviously to object, and (2) any enum type is more specific that object, so the method that takes an enum is therefore chosen by overload resolution as the better method. Point two is I hope self-explanatory, but what explains point one?

First off, there is an unfortunate deviation from the specification here. The specification says that any literal zero, that is, the number 0 actually literally appearing in the source code, may be implicitly converted to any enum type. The compiler actually implements that any constant zero may be thusly converted. The reason for that is because of a bug whereby the compiler would sometimes allow constant zeroes and sometimes not, in a strange and inconsistent manner. The easiest way to solve the problem was to consistently allow constant zeroes. You can read about this in detail here:

https://web.archive.org/web/20110308161103/http://blogs.msdn.com/b/ericlippert/archive/2006/03/28/the-root-of-all-evil-part-one.aspx

Second, the reason for allowing zeros to convert to any enum is to ensure that it is always possible to zero out a "flags" enum. Good programming practice is that every "flags" enum have a value "None" which is equal to zero, but that is a guideline, not a requirement. The designers of C# 1.0 thought that it looked strange that you might have to say

for (MyFlags f = (MyFlags)0; ...

to initialize a local. My personal opinion is that this decision has caused more trouble than it was worth, both in terms of the grief over the abovementioned bug and in terms of the oddities it introduces into overload resolution that you have discovered.

Finally, the designers of the constructors could have realized that this would be a problem in the first place, and made the signatures of the overloads such that the developer could clearly decide which ctor to call without having to insert casts. Unfortunately this is a pretty obscure issue and so a lot of designers are unaware of it. Hopefully anyone reading this will not make the same mistake; do not create an ambiguity between object and any enum if you intend the two overrides to have different semantics.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • "The reason for that is because of a bug whereby the compiler would sometimes allow constant zeroes and sometimes not" Thank you for acknowledging and pointing that out! This oddity has been a sporadic nuasance for me, for years! At last it is verified-- the ability for code to both compile and work (for years,) and magically stop working for this very reason will help me sleep better tonight. – RLH Jan 09 '13 at 15:18
  • Thanks for explaining this. I *was* wondering about the reasoning behind making 0 implicitly convertible to enums. – RichardTowers Jan 09 '13 at 15:28
1

This is apparently a known behavior and affects any function overloads where there is both an enumeration and object type. I don't understand it all, but Eric Lippert summed it up quite nicely on his blog

Earlz
  • 62,085
  • 98
  • 303
  • 499
  • Thank you for posting that reference to Lippert's blog. It's good to see that some grief went into making the decision to implement this behavior. As seems to always be the case, simple problems often arise from rather complex circumstances. – RLH Jan 09 '13 at 13:21
1

This is caused by the fact that the integer literal 0 has an implicit conversion to any enum type. The C# specification states:

6.1.3 Implicit enumeration conversions

An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result.

As a result, the most specific overload in this case is SqlParameter(string, DbType).

This does not apply for other int values, so the SqlParameter(string, object) constructor is the most specific.

Community
  • 1
  • 1
Lee
  • 142,018
  • 20
  • 234
  • 287
0

When resolving the type for an overloaded method, C# selects the most specific option. The SqlParameter class has two constructors that take exactly two arguments, SqlParameter(String, SqlDbType) and SqlParameter(String, Object). When you provide the literal 0, it can be interpreted as an Object or as a SqlDbType. Since SqlDbType is more specific than Object, it is assumed to be the intent.

You can read more about overload resolution in this answer.

Community
  • 1
  • 1
yoozer8
  • 7,361
  • 7
  • 58
  • 93