X hits on this document

878 views

0 shares

0 downloads

0 comments

291 / 396

C# LANGUAGE SPECIFICATION

interface IList { int Count { get; set; } }

interface ICounter { void Count(int i); }

interface IListCounter: IList, ICounter {}

class C { void Test(IListCounter x) { x.Count(1);// Error x.Count = 1;// Error ((IList)x).Count = 1;// Ok, invokes IList.Count.set ((ICounter)x).Count(1);// Ok, invokes ICounter.Count } }

the first two statements cause compile-time errors because the member lookup (§‎7.3) of Count in IListCounter is ambiguous. As illustrated by the example, the ambiguity is resolved by casting x 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.

In the example

interface IInteger { void Add(int i); }

interface IDouble { void Add(double d); }

interface INumber: IInteger, IDouble {}

class C { void Test(INumber n) { n.Add(1);// Error, both Add methods are applicable n.Add(1.0);// Ok, only IDouble.Add is applicable ((IInteger)n).Add(1);// Ok, only IInteger.Add is a candidate ((IDouble)n).Add(1);// Ok, only IDouble.Add is a candidate } }

the invocation n.Add(1) is ambiguous because a method invocation (§‎7.5.5.1) requires all overloaded candidate methods to be declared in the same type. However, the invocation n.Add(1.0) is permitted because only IDouble.Add is applicable. When explicit casts are inserted, there is only one candidate method, and thus no ambiguity.

In the example

278Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views878
Page views878
Page last viewedMon Dec 05 21:15:14 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments