Immutable Objects in C#

You may have heard about the benefits of immutable objects, especially from the functional programming crowd. But creating and working with immutable objects in a language like C# can be tricky.

Traditional approach

The usual way to do this is to create a constructor that takes all the data and assigns it to read-only properties. Luckily, making our properties truly read-only is now easier in C# 6 and no longer requires a backing field. So we start with something like this:

Nice, right? updatedEmail gets all the properties of person, but with a new value for Email.

C# + F# = ?

Here's a crazy idea: what if we were to write our domain object in F# and use it in the rest of our C# code? Since both languages target the CLR, interop is pretty easy. The only requirement is that the F# code has to live in a separate assembly.

The with member syntax attaches a method to our record called WithUpdatedEmail, which takes in a new email and uses the copy and update syntax to create a new object. Here's how we use it on the C# side:

Conclusion

That was a fun little experiment, and hopefully it gives you a taste of some things you can do. It's always good to look around the corner and see how other languages are doing things. It may not be feasible to rewrite an entire C# codebase in F#, but you can always incorporate ideas from F#, and perhaps a bit of code as well!