I have the following F# code which I am attempting to use to write extension methods for C#. I'm using F# 4.5 on .NET Core 2.2 (macOS), with C# 7.3 attempting to call the extension methods.
open System
open System.Runtime.CompilerServices
[<assembly: Extension>]
do ()
[<Extension>]
module Extensions =
[<CompiledName("Print"); Extension>]
type System.String with
[<Extension>]
static member inline Print(str : System.String) = Console.WriteLine(str)
[<CompiledName("Blorp"); Extension>]
type System.Object with
[<Extension>]
static member inline Blorp(o : System.Object) = Console.WriteLine("Blorp")
This is mostly taken from the F# 4.1 specification, with the assembly attribute cribbed from here. I'm using JetBrains Rider and the namespace Extensions that it's under is imported properly and the method calls even get highlighted properly in the C# function body where they get called, showing their type. But when I do dotnet run, I get a CS1061 build error for both extensions, saying the instances don't contain a definition for either method and no extension methods were found. The same methods written in C# and VB.NET work fine. What am I doing wrong? Is it no longer possible to write CLI-compatible extension methods in F#?
@dumetrulo in the comment had the solution here. The extension methods need to be let-bound functions in a module, without the enclosing type declaration:
namespace Extensions
open System
open System.Runtime.CompilerServices
[<Extension>]
module Extensions =
[<Extension>]
let Print(str : System.String) = Console.WriteLine(str)
[<Extension>]
let Blorp(o : System.Object) = Console.WriteLine("Hello World from an F# Extension Method!")
Additionally, the [<assembly: Extension>]
attribute appears to be unnecessary