Type extensions in F#

We can extend F# types by adding the equivalent of C# extension methods or something similar to partial classes in C#.

Let’s not waste time but instead get straight into the code

The type extension syntax is taken from Type Extensions (F#) which is well worth a read

type typename with
   member self-identifier.member-name =
      body
   ...
   [ end ]

[ end ] is optional in lightweight syntax.

Here’s an example of a type method for the System.String type, we’re going to add a simple Reverse function

type System.String with
    member __.Reverse = String(__.ToCharArray() |> Array.rev)

also we can create new functions like adding to a partial class

type System.String with
    member __.Append s = __.Substring(0) + s

A slightly pointless method, but at the time of writing I couldn’t think of anything more interesting.