Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>His example is confusing in part because of the (incorrect, IMO) re-use of <code>T</code> for a generic method within a generic type. The two <code>T</code> are not the same! So; let's work with a non-generic type:</p> <pre><code>class EntityBase { public virtual void Method&lt;T&gt;(T t) where T : IComparable&lt;T&gt; { // ... } } class Entity : EntityBase { public override void Method&lt;T&gt;(T t) // Error: Constraints may not be // repeated on overriding members where T : IComparable&lt;T&gt;, ISomethingElse { // ... } } </code></pre> <p>Here I added <code>ISomethingElse</code> - and clearly the 2nd method could try to use features of this second <code>T</code> - however, the caller might be:</p> <pre><code>EntityBase foo = GetEntity(); // is actually an Entity (sub-type) instance foo.Method&lt;SomeType&gt;(); ... EntityBase GetEntity() { return new Entity(); } </code></pre> <p>the base implementation does not enforce <code>ISomethingElse</code>, so the compiler does not complain that it isn't implemented. So what does the overridden method do? Hence it can't exist.</p> <p>However! If you do this at the type level instead, it <em>does</em> work, as <em>for the concrete object to exist</em> we know the constraint was enforced:</p> <pre><code>class EntityBase&lt;T&gt; where T : IComparable&lt;T&gt; { public virtual void Method(T t) { // ... } } class Entity&lt;T&gt; : EntityBase&lt;T&gt; where T : IComparable&lt;T&gt;, ISomethingElse { public override void Method(T t) { // ... can use ISomethingElse features } } </code></pre> <p>And a brief reminder - if you have a generic type with <code>&lt;T&gt;</code>, don't also use <code>&lt;T&gt;</code> in a generic method; something more specific like <code>TValue</code> etc...</p>
 

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