Note that there are some explanatory texts on larger screens.

plurals
  1. POExtension methods on base generic interfaces
    primarykey
    data
    text
    <p>I'm implementing a fluent builder pattern that requires accepting enumerables in a static extension method and iterating through its contents, while applying a functor to the enumerable's contents. As in (not the actual code, just an illustration):</p> <pre><code>public static IValidator&lt;IEnumerable&lt;T&gt;&gt; Each&lt;T&gt;( this IValidator&lt;IEnumerable&lt;T&gt;&gt; enumerable, Func&lt;T, bool&gt; action) { foreach (T value in enumerable) action(value); return validator; } </code></pre> <p>This works pretty well for enumerables but fails for inherited types/interfaces. Let's say:</p> <pre><code>IValidator&lt;IEnumerable&lt;Guid&gt;&gt; validator = ...; IEnumerable&lt;Guid&gt; guids = ...; validator.Each(guids, guid =&gt; guid != Guid.Empty); // ok IList&lt;Guid&gt; guids = ...; validator.Each(guids, guid =&gt; guid != Guid.Empty); // doesn't compile (see below) </code></pre> <p>The exception is:</p> <blockquote> <p><code>IValidator&lt;IList&lt;Guid&gt;&gt;</code> does not contain a definition for 'Each' and no extension method 'Each' accepting a first argument of type <code>IValidator&lt;IList&lt;Guid&gt;&gt;</code> could be found (are you missing a using directive or an assembly reference?</p> </blockquote> <p>My question is about the inheritance chain of <code>IValidator&lt;T&gt;</code> and, more specifically, its generic type arguments <code>T</code>. Why is type <code>IValidator&lt;IEnumerable&lt;T&gt;&gt;</code> not assignable from <code>IValidator&lt;IList&lt;T&gt;&gt;</code>? There's no circumstance I can think of on which <code>IList&lt;T&gt;</code> is not an <code>IEnumerable&lt;T&gt;</code> (given the same <code>T</code>).</p> <p>Constraining the generic argument to <code>T : IEnumerable&lt;R&gt;</code> does work but that requires two type arguments (<code>T</code> and <code>R</code>) which I'd like to avoid, if possible.</p> <p>Any thoughts? Better solutions? Thanks. </p>
    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