Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object spread equivalent in C#?

Tags:

c#

.net

I have this code:

        invoiceSurcharges.Result = from surcharge in invoiceSurcharges.Result
                                   select new ListInvoiceSurchargesGridByInvoice
                                   {
                                       
                                   };

Now, I would like to modify just one property of surcharge without having to assign each property of the object to the new one. It would be ideal if I could do something like:

        invoiceSurcharges.Result = from surcharge in invoiceSurcharges.Result
                                   select new ListInvoiceSurchargesGridByInvoice
                                   {
                                       ...surcharge,
                                       AssociatedInvoice = $"{surcharge.InvoiceSerial}-{surcharge.InvoiceYear}"
                                   };

Is there any way I could do this in C#?

like image 503
amedina Avatar asked Feb 07 '26 07:02

amedina


1 Answers

Add a copy constructor to ListInvoiceSurchargesGridByInvoice that copies all the properties from the sucharge object. You can still use property initializers to override specific properties. Consider making your objects immutable, and properties init-only, that helps avoid unintended mutation of your objects.

But an easier method is probably to use records, they are trivial to make immutable, and come with the with-expression to help creating copies with a minimal of boiler plate code:

public record ListInvoiceSurchargesGridByInvoice{
  public string AssociatedInvoice { get; init; }
  ...
}
invoiceSurcharges.Result = from surcharge in invoiceSurcharges.Result
select surcharge with { AssociatedInvoice = $"{surcharge.InvoiceSerial}-{surcharge.InvoiceYear}"};

There are some caveats when using records with EntityFramework. If that is a concern I would recommend doing some further research.

like image 126
JonasH Avatar answered Feb 09 '26 03:02

JonasH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!