Note that there are some explanatory texts on larger screens.

plurals
  1. POPros and cons of 'new' properties in C# / .Net?
    text
    copied!<p>Considering the following sample code:</p> <pre><code>// delivery strategies public abstract class DeliveryStrategy { ... } public class ParcelDelivery : DeliveryStrategy { ... } public class ShippingContainer : DeliveryStrategy { ... } </code></pre> <p>and the following sample Order class:</p> <pre><code>// order (base) class public abstract class Order { private DeliveryStrategy delivery; protected Order(DeliveryStrategy delivery) { this.delivery = delivery; } public DeliveryStrategy Delivery { get { return delivery; } protected set { delivery = value; } } } </code></pre> <p>When i derive a new type of order class, it will inherit the Delivery property of type DeliveryStrategy.</p> <p>Now, when it is given that CustomerOrders must be delivered using the ParcelDelivery strategy, we could consider '<strong>new</strong>'ing the Delivery property in the CustomerOrder class:</p> <pre><code>public class CustomerOrder : Order { public CustomerOrder() : base(new ParcelDelivery()) { } // 'new' Delivery property public new ParcelDelivery Delivery { get { return base.Delivery as ParcelDelivery; } set { base.Delivery = value; } } } </code></pre> <p>(The CustomerOrder obviously needs to ensure that is compatible (polymorph) with Order)</p> <p>This allows direct usage of the ParcelDelivery strategy on CustomerOrder without the need for casting.</p> <p>Would you consider using this pattern? why / why not?</p> <p><strong>Update</strong>: i came up with this pattern, instead of using generics, because i want to use this for multiple properties. I don't want to use generic type arguments for all these properties</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