Type Extensions in F#

There are two types of type extensions. The first would be seen more like a partial class in C# and the second are extension methods (in C# language).

Intrinsic Type Extension

So the first type of type extension is an intrinsic extension which appears “in the same namespace or module, in the same source file and in the same assembly as the type being extended” (as take from Type Extensions (F#).

Basically an intrinsic type extension can be compared to a C# partial class. It’s a way of breaking down the implementation of a class into multiple files/locations for maintainability etc.

An example of this syntax is

namespace MyNamespace

module MyType =

    type HelloWorldClass = 
        new() = {}
        member this.Hello() = printfn "hello"
        member this.World() = printfn "world"

    type HelloWorldClass with 
        member this.Exclamation = printfn"!"

The second type declaration using the with keyword to declare the extensions to the type.

Obviously when we create an instance of HelloWorldClass the methods Hello, World and Exclamation are all visible to the calling code as if they’d been writing in the one type declaration.

Options Type Extensions

Similar to the previous type extension in syntax and like C# extension methods will only be visible when loaded. For example if we want to extend a String class to add a method to capitalize the first letter of a string and have the rest lower case we might declare the following

type System.String with
   member this.CapitalizeFirstLetter =
      this.Substring(0, 1).ToUpper() + this.Substring(1).ToLower()

Notice the use of the self identifier used throughout the declaration. In usage this would now appear as an extension to the System.String class and we could use it as follows

let s = "hello"
printfn "%s" <| s.CapitalizeFirstLetter