Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.
In F# you can write an extension method like this:
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:
That’s it, just follow these 3 simple steps and you’re done:
- wrap the extension methods inside a class decorated with the [<Extension>] attribute
- 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#)
- mark the extension methods with the [<Extension>] attribute
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.
Is it possible to write just one definition that will work in both C# and F#?
Dmitri – the C# compatible version works in both F# and C#. In general, you can use extension methods defined in C# from F#.
I’ve defined some C# friendly extension methods and F# code is failing to recognize them in later files. When I had them defined as F# native, C# referring to the assembly failed to compile saying System.CodeDom was ambiguous. https://dotnetfiddle.net/JEgde1 is the F# native, https://dotnetfiddle.net/7eDv1N is the C# friendly version
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 ()