Pages

Sunday, August 19, 2012

F# Extension Methods

The F# extension method is one of my favorite feature in F#.

F# method and property to be used inside F#

F# extension methods for F# is like 
[ < AutoOpen > ]
module ExtensionMethodsOnlyInFSharp =
    type System.String with
        member this.IsFSharp() = this = "F#"
        member this.``IsF#`` with get() = this = "F#"
And it can be invoked like:
    printfn "equal to F#? %A" ("F#".IsFSharp())
    printfn "equal to F#? %A" ("F#".``IsF#``)
The IsF# is a property. So F# can define extension property! 

F# method to be used in C#

The extension method needs for C# needs an attribute. [ < System.Runtime.CompilerServices.ExtensionAttribute > ]

The extension method defined in the F# can be used in C# is like:

[< System.Runtime.CompilerServices.ExtensionAttribute >]
[< AutoOpen >]
module ExtensionMethodForCSharp = 
    [< System.Runtime.CompilerServices.ExtensionAttribute >]
    let IsFSharp(str:string) = str = "F#"

    // not possible to access from C# IDE
    [< System.Runtime.CompilerServices.ExtensionAttribute >]
    let ``IsF#``(str:string) = IsFSharp str

F# extension methods on Array

F# can define the extension method on array generic (without specifying the concrete type for 'T). It is NOT possible to declare extension method for concrete array ,such as float [].

type 'T ``[]`` with
        member this.MyExtension with get() = "my extension"

I just added code snippet support for the extension method. You can find at the codeplex project.

No comments: