<p>I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.</p>

<p>Abstract class:</p>

<pre><code>public interface IOtherObjects;

public abstract class MyObjects&lt;T&gt; where T : IOtherObjects
{
   ...

   public List&lt;T&gt; ToList()
   {
       ...
   }
}
</code></pre>

<p>Children:</p>

<pre><code>public class MyObjectsA : MyObjects&lt;OtherObjectA&gt; //(where OtherObjectA implements IOtherObjects)
{


}

public class MyObjectsB : MyObjects&lt;OtherObjectB&gt; //(where OtherObjectB implements IOtherObjects)
{


}
</code></pre>

<p>Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to <em>ToList</em> method of the <em>MyObjects</em> base class, as we do not specifically know the type of T at this point. </p>

<p><strong>EDIT</strong>
As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.</p>

<p><strong>EDIT</strong>
@Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)</p>

<p>@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds</p>

<p><strong>EDIT</strong> @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.</p>

<p><strong>EDIT</strong>@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects. </p>

<p>@Rob <strong>Again</strong> Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.</p>

<p><strong>QUALIFYING EDIT</strong> in case I have been a little confusing</p>

<p>To be more precise, (I may have let my latest implementation of this get it too complex):</p>

<p>lets say I have 2 object types, B and C inheriting from object A.</p>

<p>Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A. </p>

<p>The above example was a watered-down example of the <em>List Of Less Specific</em> problem's latest incarnation.</p>

<p>Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand</p>

<p>@Rob <strong>Yet Again</strong> and Sara</p>

<p>Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.</p>

<p>The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).</p>

<p>My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.</p>

<p>I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it.</p>

[{'answer_id': 53402, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': "<p>In your case MyObjectsA and MyObjectsB don't have common predecessor. Generic class is template for <em>different</em> classes not a common base class. If you want to have common properties in different classes use interfaces. You can't call <em>ToList</em> in a loop cause it has different signature in different classes. You can create ToList that returns <em>objects</em> rather than specific type.</p>\n"}, {'answer_id': 53403, 'author': 'Sara Chipps', 'author_id': 4140, 'author_profile': 'https://Stackoverflow.com/users/4140', 'pm_score': 2, 'selected': False, 'text': "<p>why do you have a collection of MyObjects? Is there a specific reason you don't have a List?</p>\n"}, {'answer_id': 53406, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 1, 'selected': False, 'text': "<p>You can still probably access the ToList() method, but since you are unsure of the type, won't this work?</p>\n\n<pre><code>foreach(var myObject in myObjectsList)\n    foreach(var obj in myObject.ToList())\n        //do something\n</code></pre>\n\n<p>Of course this will only work on C# 3.0.</p>\n\n<p>Note that the use of var is merely to remove the requirement of knowing what type the lists contain; as opposed to Frank's comments that I have delusions that var will make typing dynamic.</p>\n"}, {'answer_id': 53418, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': -1, 'selected': False, 'text': '<p>Generics are used for static time type checks <strong>not</strong> runtime dispatch. Use inheritance/interfaces for runtime dispatch, use generics for compile-time type guarantees.</p>\n\n<pre><code>interface IMyObjects : IEnumerable&lt;IOtherObjects&gt; {}\nabstract class MyObjects&lt;T&gt; : IMyObjects where T : IOtherObjects {}\n\nIEnumerable&lt;IMyObjects&gt; objs = ...;\nforeach (IMyObjects mo in objs) {\n    foreach (IOtherObjects oo in mo) {\n        Console.WriteLine(oo);\n    }\n}\n</code></pre>\n\n<p>(Obviously, I prefer Enumerables over Lists.)</p>\n\n<p><strong>OR</strong> Just use a proper dynamic language like VB. :-)</p>\n'}, {'answer_id': 53446, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 1, 'selected': False, 'text': '<p>OK, I am confused, the following code works fine for me (curiosity got the better of me!):</p>\n\n<pre><code>// Original Code Snipped for Brevity - See Edit History if Req\'d\n</code></pre>\n\n<p>Or have I missed something?</p>\n\n<h2>Update Following Response from OP</h2>\n\n<p>OK now I am really confused..\nWhat you are saying is that you want to get a List of <em>Typed</em> values from a generic/abstract List? (the child classes therefore become irrelevant).</p>\n\n<p>You cannot return a Typed List if the Types are children/interface implementors - they do not match! You can of course get a List of items that are of a specific type from the abstract List like so:</p>\n\n<pre><code>    public List&lt;OfType&gt; TypedList&lt;OfType&gt;() where OfType : IOtherObjects\n    {\n        List&lt;OfType&gt; rtn = new List&lt;OfType&gt;();\n\n        foreach (IOtherObjects o in _objects)\n        {\n            Type objType = o.GetType();\n            Type reqType = typeof(OfType);\n\n            if (objType == reqType)\n                rtn.Add((OfType)o);\n        }\n\n        return rtn;\n    }\n</code></pre>\n\n<p>If I am still off-base here can you please reword your question?! (It doesn\'t seem like I am the only one unsure of what you are driving at). I am trying to establish if there is a misunderstanding of generics on your part.</p>\n\n<h2>Another Update :D</h2>\n\n<p>Right, so it looks like you want/need the option to get the typed List, or the base list yes?</p>\n\n<p>This would make your abstract class look like this - you can use ToList to get the concrete type, or ToBaseList() to get a List of the interface type. This should work in any scenarios you have. Does that help?</p>\n\n<pre><code>public abstract class MyObjects&lt;T&gt; where T : IOtherObjects\n{\n    List&lt;T&gt; _objects = new List&lt;T&gt;();\n\n    public List&lt;T&gt; ToList()\n    {\n        return _objects;\n    }\n\n    public List&lt;IOtherObjects&gt; ToBaseList()\n    {\n        List&lt;IOtherObjects&gt; rtn = new List&lt;IOtherObjects&gt;();\n        foreach (IOtherObjects o in _objects)\n        {\n            rtn.Add(o);\n        }\n        return rtn;\n    }\n}\n</code></pre>\n\n<h2>Update #3</h2>\n\n<p>It\'s not really a "cludgy" workaround (no disrespect taken) - thats the only way to do it.. I think the bigger issue here is a design/grok problem. You said you had a problem, this code solves it. But if you were expecting to do something like:</p>\n\n<pre><code>public abstract class MyObjects&lt;T&gt; where T : IOtherObjects\n{\n    List&lt;T&gt; _objects = new List&lt;T&gt;();\n\n    public List&lt;IOtherObjects&gt; Objects\n    { get { return _objects; } }\n}\n#warning This won\'t compile, its for demo\'s sake.\n</code></pre>\n\n<p>And be able to pick-and-choose the types that come out of it, how else <em>could</em> you do it?! I get the feeling you do not really understand what the point of generics are, and you are trying to get them to do something they are not designed for!?</p>\n'}, {'answer_id': 84484, 'author': 'Amy B', 'author_id': 8155, 'author_profile': 'https://Stackoverflow.com/users/8155', 'pm_score': 2, 'selected': True, 'text': '<p>If you have</p>\n\n<pre><code>class B : A\nclass C : A\n</code></pre>\n\n<p>And you have</p>\n\n<pre><code>List&lt;B&gt; listB;\nList&lt;C&gt; listC;\n</code></pre>\n\n<p>that you wish to treat as a List of the parent type</p>\n\n<p>Then you should use</p>\n\n<pre><code>List&lt;A&gt; listA = listB.Cast&lt;A&gt;().Concat(listC.Cast&lt;A&gt;()).ToList()\n</code></pre>\n'}, {'answer_id': 98008, 'author': 'johnc', 'author_id': 5302, 'author_profile': 'https://Stackoverflow.com/users/5302', 'pm_score': 0, 'selected': False, 'text': '<p>I have recently found the </p>\n\n<pre><code>List&lt;A&gt;.Cast&lt;B&gt;().ToList&lt;B&gt;()\n</code></pre>\n\n<p>pattern. </p>\n\n<p>It does exactly what I was looking for,</p>\n'}]
['https://Stackoverflow.com/questions/53395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5302/']