When interacting with C# libraries, I find myself wanting C#'s null coalescing operator both for Nullable
structs and reference types.
Is it possible to approximate this in F# with a single overloaded operator that inlines the appropriate if
case?
Yes, using some minor hackery found in this SO answer "Overload operator in F#".
At compiled time the correct overload for an usage of either
('a Nullable, 'a) ->'a
or('a when 'a:null, 'a) -> 'a
for a single operator can be inlined. Even('a option, 'a) -> 'a
can be thrown in for more flexibility.To provide closer behavior to c# operator, I've made default parameter
'a Lazy
so that it's source isn't called unless the original value isnull
.Example:
Implementation:
NullCoalesce.fs [Gist]:
Alternatively I made a library that utilizes this technique as well as computation expression for dealing with Null/Option/Nullables, called FSharp.Interop.NullOptAble
It uses the operator
|?->
instead.