Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do you use foreach on a base class using generics?
    primarykey
    data
    text
    <p>This question is as a result of trying <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet's</a> answer to <a href="https://stackoverflow.com/questions/944296/">this question</a>.</p> <p>So I have the following code based in the question and answer from the above question link.</p> <pre><code> public abstract class DeliveryStrategy { } public class ParcelDelivery : DeliveryStrategy { } public class ShippingContainer : DeliveryStrategy { } public abstract class Order&lt;TDelivery&gt; where TDelivery : DeliveryStrategy { private TDelivery delivery; protected Order(TDelivery delivery) { this.delivery = delivery; } public TDelivery Delivery { get { return delivery; } set { delivery = value; } } } public class CustomerOrder : Order&lt;ParcelDelivery&gt; { public CustomerOrder() : base(new ParcelDelivery()) { } } public class OverseasOrder : Order&lt;ShippingContainer&gt; { public OverseasOrder() : base(new ShippingContainer()) { } } </code></pre> <p>I'm trying understand generics more to improve my skill set, so I have the question of: Now how can I use foreach to loop through a collection of "Orders"? I'm using C#2.0.</p> <p>Code Example of what I'm trying to do (does not compile).</p> <pre><code>List&lt;Order&gt; orders = new List&lt;Order&gt;(); orders.Add(new CustomerOrder()); orders.Add(new CustomerOrder()); orders.Add(new OverseasOrder()); orders.Add(new OverseasOrder()); foreach (Order order in orders) { order.Delivery.ToString(); } </code></pre> <p><b>EDIT: Added OverseasOrder to give a better example.</b></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