Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Generics - Resolved - How to solve the ambiguous compiler error calling a method of passed generic type; e.g., IXList.Head() and IYList.Head()
    primarykey
    data
    text
    <p>The emphasis of my question is with <strong>C# Generics</strong> and the passing of the interface <strong>IXList</strong> -or- <strong>IYList</strong> to this '<strong>GetAllValues</strong>()' method. The goal is common code for calling <code>GetAllValues&lt;IXList&gt;()</code> -or- <code>GetAllValues&lt;IYList&gt;()</code>.</p> <p>09-21-13 Follow up: I have learned that: <code>where Z : IXList, IYList</code> means that Z is of type <code>IXList</code> and <code>ITList</code> -- given this understanding one might try <code>where Z : class</code> - this is at best a lateral step of still not working because then <code>Z.anything</code> ... <code>anything</code> is not found, the compiler is clueless about <code>Z</code>...</p> <p>Can the actual type of Z passed be tested and then conditional run-time code pick correct casted <code>list</code> to call .Head(), .Get(), and .Next() accordingly? e.g., <code>((IXList)list).Head();</code> -or- <code>((IYList)list).Head();</code> <strong>[[ Yes it is possible, please see 2nd answer with code below dated 09-24-13.]]</strong></p> <p>09-29-13 Follow up: And finally, answer/solution <strong>#3</strong> posted below moves the final solution to a more object oriented one. And thus, this 3rd solution <strong>renders moot</strong> my initial question on how to ask the type of generic and how to solve the compiler ambiguity error encountered initially. <strong>[[ Please see answer/solution #3, with code below dated 09-29-13.]]</strong></p> <pre><code> internal static IEnumerable&lt;int&gt; GetAllValues&lt;Z&gt;(Z list) where Z : IXList, IYList { try { list.Head(); // Error 344 - The call is ambiguous between the following // methods or properties: 'IXList.Head()' and 'IYList.Head()' } catch (Exception) { yield break; } do { IntPtr lineItemPointer; int x = list.Get(); // Error 345 - The call is ambiguous between the following // methods or properties: 'IXList.Get()' and 'IYList.Get()' yield return x; try { list.Next(); // Error 346 -The call is ambiguous between the following // methods or properties: 'IXList.Next()' and 'IYList.Next()' } catch (Exception) { yield break; } } while (true); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload