Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing an overloaded function to iterate over a List<Base>
    primarykey
    data
    text
    <p>Given the following class structure:</p> <pre><code>class Base {} class DerivedA: Base {} class DerivedB: Base {} class Container { public List&lt;Base&gt; Items { get; } } </code></pre> <p>where the list of Derived objects grows over time as my application develops more functionality. I'm trying to do:</p> <pre><code>Container container = ReturnsContainer(); foreach (var item in container.Items) { doStuff(item); } </code></pre> <p>where doStuff(item) is overloaded by derived type.</p> <pre><code>void doStuff(DerivedA) {} void doStuff(DerivedB) {} </code></pre> <p>That doesn't work as the compiler says "cannot convert from 'Base' to 'DerivedA'" and "The best overloaded method match doStuff(DerivedA) has some invalid arguments". The best approach I can come up with is:</p> <pre><code>Container container = ReturnsContainer(); foreach (var item in container.Items) { if (item is DerivedA) { doStuff((DerivedA)item); } else if (item is DerivedB) { doStuff((DerivedB)item); } } </code></pre> <p>Any thoughts on how I can make this cleaner? Since my Derived types will only grow over time, I would have to go back and add to this long if structure to continue to make this work.</p> <p>I think the container.Items.OfType&lt;> solution would translate to a growing (and unnecessary) performance hit as the number of Derived types increases.</p> <p>Do I have to use generic delegates for this? Seems like an overly complex solution for something that <em>feels</em> like it should be simple polymorphism.</p> <p><strong>Edit</strong>: For further clarity, let's say the Base and Derived type hierarchy is on a separate API layer and is not modifiable (final classes). The solution has to work with the existing inheritance structure and cannot extend the Base and Derived objects. Though the API layer can grow new Derived classes as time goes on.</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.
 

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