Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access derived class members from an interface?
    text
    copied!<p>I have three classes; Stamp, Letter and Parcel that implement an interface IProduct and they also have some of their own functionality. </p> <pre><code>public interface IProduct { string Name { get; } int Quantity { get; set; } float Amount { get; } } public class Stamp : IProduct { public string Name { get { return "Stamp"; } } public int Quantity { get; set; } public float Amount { get; set; } public float UnitPrice { get; set; } } public class Letter : IProduct { public string Name { get { return "Letter"; } } public int Quantity { get; set; } public float Amount { get; set; } public float Weight { get; set; } public string Destination { get; set; } } public class Parcel : IProduct { public string Name { get { return "Parcel"; } } public int Quantity { get; set; } public float Amount { get; set; } public float Weight { get; set; } public string Destination { get; set; } public int Size { get; set; } } public static class ShoppingCart { private static List&lt;IProduct&gt; products = new List&lt;IProduct&gt;(); public static List&lt;IProduct&gt; Items { get { return products; } } } </code></pre> <p><strong>Why can't I access the additional members of derived classes from a <code>List&lt;IProduct&gt;</code> ?</strong> </p> <pre><code>ShoppingCart.Items.Add(new Stamp { Quantity = 5, UnitPrice = 10, Amount = 50 }); ShoppingCart.Items.Add(new Letter { Destination = "US", Quantity = 1, Weight = 3.5f }); ShoppingCart.Items.Add(new Parcel { Destination = "UK", Quantity = 3, Weight = 4.2f, Size = 5 }); foreach (IProduct product in ShoppingCart.Items) { Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}", product.Name, product.Quantity, product.Amount); } </code></pre> <p>I thought of using generics, but in that case I will have to write separate code for each specific type of product. </p> <pre><code>public static class ShoppingCart&lt;T&gt; where T : IProduct { private static List&lt;T&gt; items = new List&lt;T&gt;(); public static List&lt;T&gt; Items { get { return items; } } } ShoppingCart&lt;Stamp&gt;.Items.Add(new Stamp { Quantity = 5, Amount = 10, UnitPrice = 50 }); ShoppingCart&lt;Letter&gt;.Items.Add(new Letter { Destination = "US", Quantity = 1, Weight = 3.5f }); foreach (Stamp s in ShoppingCart&lt;Stamp&gt;.Items) { Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}", s.Name, s.Quantity, s.Amount); } foreach (Letter l in ShoppingCart&lt;Letter&gt;.Items) { Console.WriteLine("Name: {0}, Destination: {1}, Weight: {2}", l.Name, l.Destination, l.Weight); } </code></pre> <p>Isn't there any kind of design pattern for this kind of problem. Factory Pattern?</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