Functional Inspiration – Revisiting the With extension method

Return to the very first post for improvement

This is the fourth entry of a blog series about how functional programming, and the F# training I recently went to, gives me inspiration in my day-to-day work in C#. It is going to propose an other implementation of the “With” method, which this time deals with immutable data structures.

No long explanation today, here is a very simple immutable class representing the same Person as in the first post :

We can this time see that all the fields are defined “readonly”, making that data structure immutable. As the value of the fields can only be modified inside the constructor, we will not be able to use a delegate parameter as previously. We will have to find a way to modify the values in the constructor.

To do so, we define a second (private) constructor. Surprise ! The Irrelevantable construct shows up :

When this constructor is called, it populates the properties using either the source Person’s properties, either the following arguments, depending on whether they are “relevant”. If this constructor is called with a single “relevant” value, it acts quite as out original “With” method.

And using the C#4.0 default values capabilities, we can make things even better :