-
Notifications
You must be signed in to change notification settings - Fork 93
Description
The first example in this section has a bug. Here is that example and surrounding narrative:
Interface members are accessed through member access (§11.7.6) and indexer access (§11.7.10.3) expressions of the form
I.M
andI[A]
, whereI
is an interface type,M
is a method, property, or event of that interface type, andA
is an indexer argument list.For interfaces that are strictly single-inheritance (each interface in the inheritance chain has exactly zero or one direct base interface), the effects of the member lookup (§11.5), method invocation (§11.7.8.2), and indexer access (§11.7.10.3) rules are exactly the same as for classes and structs: More derived members hide less derived members with the same name or signature. However, for multiple-inheritance interfaces, ambiguities can occur when two or more unrelated base interfaces declare members with the same name or signature. This subclause shows several examples, some of which lead to ambiguities and others which don’t. In all cases, explicit casts can be used to resolve the ambiguities.
Example: In the following code
interface IList { int Count { get; set; } } interface ICounter { void Count(int i); } interface IListCounter : IList, ICounter {} class C { void Test(IListCounter x) { /*17*/ x.Count(1); // Error /*18*/ x.Count = 1; // Error /*19*/ ((IList)x).Count = 1; // Ok, invokes IList.Count.set /*20*/ ((ICounter)x).Count(1); // Ok, invokes ICounter.Count } }the first two statements cause compile-time errors because the member lookup (§11.5) of
Count
inIListCounter
is ambiguous. As illustrated by the example, the ambiguity is resolved by castingx
to the appropriate base interface type. Such casts have no run-time costs—they merely consist of viewing the instance as a less derived type at compile-time.
The only compilation error reported is for Line 18:
Library.cs(18,9): error CS1656: Cannot assign to 'Count' because it is a 'method group'
If I disable that line, no error results from Line 17, in any csc compiler version since V1!
BTW, this example has been in the Ecma spec since V1. Perhaps this case was an error in a pre-V1 release when the first MS spec was first written!