Q:

How to check for `null` from Newtonsoft when the compiler insists that it isn't possible?

Our project is mixed C# & F# with the ASP.NET Core. ASP.NET core defaults to Newtonsoft for serializing/deserializing everywhere, and the swagger documentation generation (nswag) also relies on CLI(Mutable)-like DTOs to generate correct types.
Our DTOs are defined in F# like so:
[<CLIMutable>]
type Query =
    { Status: string
      Offset: int
      Limit: int }

Which makes it trivial for Newtonsoft to serialize, and nswag to generate swagger doc.
But..! I'm having a extremely hard time with the null/option "mismatch". C#/Newtonsoft/NSwag insists on using null, and will not understand F#'s option. So in my F# I have to check for nulls and convert them to option; and also convert my options back to nulls when converting from domain back to DTO.
But F# insists that null isn't a possible to the point where I'm not even allowed to check: The compiler gives me: "The type {...} does not have 'null' as a proper value". But fact is that runtime, it IS null because that's how Newtonsoft works. Newtonsoft is the .NET standard it seems, so I don't think using something else is feasible unfortunately.
How can I check for nulls even though F# thinks it's impossible for it to be null?

A:

A simple way to overcome this (in general) is to box the value before checking for null.
let isReallyNull value = value |> box |> isNull
Then you can check the object instances returned by Newtonsoft in your normal logic:
if dto |> isReallyNull
then None
else Some dto

Here's a complete example using Unchecked.defaultof to generate a null value for a type the compiler says can't be null:
[<CLIMutable>]
type MyDto =
    {
        Status: string
        Offset: int
        Limit: int
    }

let isReallyNull value = value |> box |> isNull

let dto = Unchecked.defaultof<MyDto>

// if dto |> isNull (* Compiler complains that MyDto does not have null as a proper value *)
if dto |> isReallyNull
then printfn "The DTO is null"
else printfn "The DTO is non-null"

