lundi 25 juillet 2016

General purpose immutable classes in C#

I am writing code in a functional style in C#. Many of my classes are immutable with methods for returning a modified copy of an instance.

For example:

sealed class A
{
    readonly X x;
    readonly Y y;

    public class A(X x, Y y)
    {
        this.x = x;
        this.y = y;
    }

    public A SetX(X nextX)
    {
        return new A(nextX, y);
    }

    public A SetY(Y nextY)
    {
        return new A(x, nextY);
    }
}

This is a trivial example, but imagine a much bigger class, with many more members.

The problem is that constructing these modified copies is very verbose. Most of the methods only change one value, but I have to pass all of the unchanged values into the constructor.

Is there a pattern or technique to avoid all of this boiler-plate when constructing immutable classes with modifier methods?

Note: I do not want to use a struct for reasons discussed elsewhere on this site.

Aucun commentaire:

Enregistrer un commentaire