Functional Inspiration – The With extension method

Adding a “With” extension method mimicking F#

This is the first 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#. The first one will show how you can build a “with”-like feature in C#.

One of the many features of F# that stroke me during Robert Pickering’s “Beginning F#” course, was the Record Type and its ease of use. For those of you that don’t know F#, a record type can be compared with a Tuple whose properties would be named.

For instance, this F# snippet defines a Record Type Person with two properties Name and Age.

The “with” keyword allow us to define “someoneElse” as a copy of “someone”, stating only the values of the properties to change.

In a project I have been working on recently, I had exactly the same need of defining a new instance with very little changes, but in C#. In order to do this, I wrote a simple extension method, base on the ICloneable interface :

I find this construct quite expressive and readable, but please note that there are several drawbacks :

The C# objet has to be mutable. Its “Age” property is set after the object is created by the Clone method. Even though the Clone method could have used a copy constructor instead of setting properties, the generic With method must overwrite the properties values. Addendum : this problem is now solved in “Revisiting the With extension method”.

The syntax to use in order to modify more than one property is less readable, because a lambda expression with multiple instructions has to be written between accolades.

In the end, whatever you do, someoneElse will be 30, and his name is Luc.