Note that there are some explanatory texts on larger screens.

plurals
  1. POImplicit conversion between types in C#
    text
    copied!<p>I have the following business objects:</p> <pre><code> public abstract class Product { public int Id { get; set; } public bool OnStock { get; set; } } public class ProductForImport : Product { public int ImportId { get; set; } } public class ProductForExport : Product { public int ExportId { get; set; } public bool IsExportable { get; set; } public bool IsUsable { get; set; } public string OtherParam {get; set;} public static implicit operator ProductForExport(ProductForImport pfi) { ProductForExport p = new ProductForExport(); p.Id = pfi.Id; p.IsExportable = true; p.ExportId = 0; return p; } } </code></pre> <p>so I can convert between the two types:</p> <pre><code> static void Main(string[] args) { ProductForExport pfe = new ProductForExport(); pfe.Id = 1; pfe.OnStock = true; ProductForImport pfi = new ProductForImport(); pfi.ImportId = 200; ProductForExport pfe2 = (ProductForExport)pfi; } </code></pre> <p>this works OK. </p> <p>I have 100.000 ProductsForImport items. If I understand correctly, if I convert them to ProductsForExport items, I'll have 100.000 +100.000 items in memory - that's reasonable.</p> <p>My problem is: I have to send these "ProductForExport" objects through JSON services, each service just need some subset of the properties of each type:</p> <p>servicecall1 should return <code>ProductForExport1{ExportId,IsExportable}</code></p> <p>servicecall2 should return <code>ProductForExport2{ExportId,IsUsable}</code></p> <p>Question: should I write an implicit conversion similar to the above example for these new types - <code>ProductForExport1</code> and <code>ProductForExport2</code> (so basically create 100.000+100.000 new objects)</p> <p>or </p> <p>somehow can I just "hide" the unwanted properties with some magic from the original type without the need to create new instances?</p> <p>thanks,</p> <p>b.</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