Note that there are some explanatory texts on larger screens.

plurals
  1. POSomeList<T> : List<T> can't be cast as List<T>?
    text
    copied!<p>See comment in Main(). Why can't I perform the following?</p> <pre><code> public class SomeList&lt;T&gt; : List&lt;T&gt; { public SomeList(List&lt;T&gt; existing) { foreach (var item in existing) Add(item); } public override string ToString() { return "I'm a better list."; } } internal interface IReadStuff&lt;T&gt; { List&lt;T&gt; ReadStuff(); } public class ReaderStrategy&lt;Foo&gt; : IReadStuff&lt;Foo&gt; { public List&lt;Foo&gt; ReadStuff() { return new List&lt;Foo&gt;(); } } public class Foo {} public class Main { public Main() { var reader = new ReaderStrategy&lt;Foo&gt;(); // This works, but type is List&lt;Foo&gt;, not SomeList&lt;Foo&gt; List&lt;Foo&gt; aList = reader.ReadStuff(); // This does not compile, but is what I want to do: SomeList&lt;Foo&gt; aBetterList = reader.ReadStuff(); // This compiles, but always generates null for aBetterList: SomeList&lt;Foo&gt; anotherBetterList = reader.ReadStuff() as SomeList&lt;Foo&gt;; // This is funky but works: SomeList&lt;Foo&gt; works = new SomeList&lt;Foo&gt;(reader.ReadStuff()); } } </code></pre> <p>I am struggling understanding how to use generics with inherited types. I have a need for the above because I want to extend the functionality of <code>List&lt;T&gt;</code> is some special way, for example see <code>SomeList&lt;T&gt; overrides ToString()</code>. However, I want to keep my factory strategy using .Net generic <code>List&lt;T&gt;</code>. Is there a way to make this work?</p> <p><strong>Edit</strong></p> <p>I added a constructor that accepts <code>List&lt;T&gt;</code> and adds to <code>SomeList&lt;T&gt;</code>. This doesn't seem natural, but works. This is an expensive operation, especially if <code>List&lt;T&gt;</code> is large. </p> <p>My question title was not the best, what I was striving for was an example showing a better way to do this.</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