using the following code, all cause a compilation error (.net 2):
var headers = new WebHeaderCollection();
var a = headers[0];
var b = headers[(int)0];
const int FIRST_HEADER = 0;
var c = headers[FIRST_HEADER];
All fail with: The call is ambiguous between the following methods or properties: ‘System.Net.WebHeaderCollection.this[System.Net.HttpRequestHeader]’ and ‘System.Net.WebHeaderCollection.this[System.Net.HttpResponseHeader]’.
I can understand to some extent why (a) would fail, as the overloads accept the HttpRequestHeader/HttpResponseHeader enums; but (b) and (c) are implicitly cast to type int.
The following works:
var headers = new WebHeaderCollection();
int index = 0;
var d = headers[index];
I only came across this when writing some tests, and needed the ability to prove that an expected header was added (and in my scenario would always be the only one!)
Why do i have to declare a variable of type int to use this overload?
In all cases, the expression is deemed to be “a constant expression with value zero” – which is implicitly convertible to any enum type.
Your later code works because you’re effectively losing the const-ness, so that removes the implicit conversion.
In fact, there’s a bug in the C# compiler around this, which means it treats any constant expression with value zero, not just integer values, as convertible to any enum type – so this works too, but shouldn’t: