Search code examples
c#cloneextension-methods

How would I go about creating a ReturnAlteredObject extension method?


TL;DR: I want an extension method that can extend object and can be used like this:

var OtherInstance = MyObject.Altered(new { Prop1 = "123", Prop6 = 4 });

I'd expect all properties of OtherInstance to be the same as MyObject, except for Prop1 and Prop6. I don't expect/require it to deep-clone.


Background

I have an MVC page that allows the user to search to display a list of data.

My page model has various filter properties, as well as a page number.

At the bottom of my list of data I have a link to the next page created using Html.ActionLink. I pass in a copy of the model, with the page number incremented:

<%= Html.ActionLink("Next", "Index", new
{
    Page = (Model.Page ?? -1) + 1,
    Model.SortProperties,
    Model.SortDescending,
    Model.FilterId,
    Model.FilterApprovalsLevelId,
    Model.FilterStandardTypeId,
    Model.FilterApprovalsBodyReferenceNumber,
    Model.FilterCertificateOrApprovalNumber
}, new { id = "next-page" })%>

If I add new filters to my model it's easy to forget to add the property in here, so I was hoping to be able to clone the object and alter 1 or 2 properties fluently, like so:

<%= Html.ActionLink("Next", "Index", Model.Altered(new
{
    Page = (Model.Page ?? -1) + 1
}), new { id = "next-page" })%>

Solution

  • You can use RouteValueDictionary class to achive that. First Create and instance of RouteValueDictionary from your model and then add to the dictionary the rest of the properties here is the pseudo code:

    <%= Html.ActionLink("Next", "Index", new RouteValueDictionary(Model).AddAndReturn("Page", (Model.Page ?? -1) + 1), new { id = "next-page" })%>