Search code examples
c#f#nulloption-typerecord

Return record option as null when calling from C#


Is it ever possible to return record option value from F# to C# as null value? I want to encapsulate some logic in F# assembly, and hide as much as I can behind facade being "more natural to C#". Here's some synthetic example:

type Data = { DataField1: int; DataField2: string }

And code to return to C# would look like this:

type SomeFacade() =
    let data = Some { DataField1 = 1; DataField2 = "hello" }  

    member x.GetData() = if Option.isSome data then Option.get data else null

But it is not allowed to use null value.

  • I could try to use [<AllowNullLiteral>] attribute, but it can't be used on record types.
  • I could use Class instead of Record but it would be more complicated to work with it inside F# as most of work are supposed to be done inside the F# part. And I like the extremely convenient way of creating record values by copying another record value using with keyword.
  • It is even possible to use Data as record inside F# assembly and convert it to some intermediate class DataClass when exposing to C# assemblies, but it looks awkward.

Is there any solution? (I'm not going to use null values inside F# code but I would like to return null values to C# code).


Solution

  • For record types,

    Operators.Unchecked.defaultof<Data>
    

    is null (just tested using fsi)

    This is probably the simplest solution