JustinM
JustinM

Reputation: 1013

Difficulty getting "intrinsic type extensions" visible from C#

The Microsoft F# docs say...

Intrinsic type extensions must be defined in the same file and in the same namespace or module as the type they're extending. Any other definition will result in them being optional type extensions.

When I define extensions in the SAME namespace and SAME file but DIFFERENT module I can't use the extensions from C#:

namespace Contacts

module AddressBookTypes =

    type Person = { FirstName: string; LastName: string }

module AddressBookFunctions =

    open AddressBookTypes

    let fullName (p: Person) = p.FirstName + " " + p.LastName

type Person with
    member public me.FullName = me |> fullName // Not visible in C#

let getFullName1 (p: Person) = p.FullName // Visible locally

Is the documentation correct? Or must intrinsic extensions be defined in the same module too? Here is a very simple VS solution on Github that illustrates the problem.

Upvotes: 1

Views: 83

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

So when you define an extension in a different module it becomes an optional type extension

Optional extension members are also not visible to C# or Visual Basic consumers. They can only be consumed in other F# code.

If you want the extension defined in the different module to be consumed in C# code you should use extension methods:

open System.Runtime.CompilerServices
open Contacts.AddressBookTypes
open Contacts.AddressBookFunctions

[<Extension>]
type PersonExtensions =
    [<Extension>]
    static member FullName(person: Person) = fullName person

Upvotes: 2

Related Questions