F# – Make extension methods visible to C#

In F# you can write an extension method like this:

image

Whilst this will work perfectly fine in your F# code, the extension method will not be visible to any C# code using the FileInfo type because F# and C# compiles extension methods differently.

To make C#-compatible extension methods in F#, here’s what you need to do instead:

image

That’s it, just follow these 3 simple steps and you’re done:

  1. wrap the extension methods inside a class decorated with the [<Extension>] attribute
  2. write the extension methods as static members where the first argument is of the type which should be extended (like how you would write an extension method in C#)
  3. mark the extension methods with the [<Extension>] attribute

 

Learn to build Production-Ready Serverless applications

Want to learn how to build Serverless applications and follow best practices? Subscribe to my newsletter and join over 3,000 AWS & Serverless enthusiasts who have signed up already.
As a BONUS, you will receive early access and discount for my new AppSync course.

4 thoughts on “F# – Make extension methods visible to C#”

  1. Dmitri – the C# compatible version works in both F# and C#. In general, you can use extension methods defined in C# from F#.

  2. For those of us having troubles, it is needed to provide the attribute on the assembly too to make it work, it doesn’t compile in VB.net code otherwise.

    you can do so with an Attribute.fs file containing this:

    module AssemblyInfo
    open System.Runtime.CompilerServices
    []
    do ()

Leave a Comment

Your email address will not be published.