wallymathieu / with

Extensions and classes to make immutable c# easier to use. Obsolete with introduction of records in C# 9.
MIT License
18 stars 1 forks source link

Expose lens abstraction to c# #47

Closed wallymathieu closed 4 years ago

wallymathieu commented 5 years ago

In order to be able to create prepared copy expressions for more properties the easiest way is to expose lenses:

var copyUpdateExpression=
                    LensBuilder<AClassWithManyProperties>
                        .Of<int, string>((m, v1, v2) => m.MyProperty == v1 && m.MyProperty2 == v2)
                        .And<string, string>((m, v1, v2) => m.MyProperty3 == v1 && m.MyProperty4 == v2)
                        .And(m=>m.Property5)
                        .BuildPreparedCopy()

this enables you to use the copyUpdateExpression to get clones of immutable style c# classes with properties set

A concrete example

using With;
...
public class CustomerChangeHandler
{
    // start with initializing the copy update expression once (main cost is around parsing expressions)
    private static readonly IPreparedCopy<Customer, int, string, IEnumerable<string>> CopyUpdate =
        LensBuilder<Customer>.Of(m => m.Id).And(m => m.Name).And(m => m.Preferences)
                          .BuildPreparedCopy();
    public void Handle()
    {
        // fetch customer, say:
        var customer = new Customer(id:1, name:"Johan Testsson");
        // change that customer with new values:
        var change = CopyUpdate.Copy(customer, NextId(), "Erik Testsson", new []{"Swedish fish"});
        // ...
    }
}