In F# you can write an exten­sion method like this:

image

Whilst this will work per­fectly fine in your F# code, the exten­sion method will not be vis­i­ble to any C# code using the File­Info type because F# and C# com­piles exten­sion meth­ods differently.

To make C#-compatible exten­sion meth­ods in F#, here’s what you need to do instead:

image

That’s it, just fol­low these 3 sim­ple steps and you’re done:

  1. wrap the exten­sion meth­ods inside a class dec­o­rated with the [<Exten­sion>] attribute
  2. write the exten­sion meth­ods as sta­tic mem­bers where the first argu­ment is of the type which should be extended (like how you would write an exten­sion method in C#)
  3. mark the exten­sion meth­ods with the [<Exten­sion>] attribute
Share

2 Responses to “F# – Make extension methods visible to C#”

  1. Dmitri says:

    Is it pos­si­ble to write just one def­i­n­i­tion that will work in both C# and F#?

  2. theburningmonk says:

    Dmitri — the C# com­pat­i­ble ver­sion works in both F# and C#. In gen­eral, you can use exten­sion meth­ods defined in C# from F#.

Leave a Reply