Last active
May 13, 2022 16:38
-
-
Save jbtule/8477768 to your computer and use it in GitHub Desktop.
Null Coalesce Operator for F# (|??), works with option, Nullable, and c# reference types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//inspired by http://stackoverflow.com/a/2812306/637783 | |
type NullCoalesce = | |
static member Coalesce(a: 'a option, b: 'a Lazy) = match a with Some a -> a | _ -> b.Value | |
static member Coalesce(a: 'a Nullable, b: 'a Lazy) = if a.HasValue then a.Value else b.Value | |
static member Coalesce(a: 'a when 'a:null, b: 'a Lazy) = match a with null -> b.Value | _ -> a | |
let inline nullCoalesceHelper< ^t, ^a, ^b, ^c when (^t or ^a) : (static member Coalesce : ^a * ^b -> ^c)> a b = | |
((^t or ^a) : (static member Coalesce : ^a * ^b -> ^c) (a, b)) | |
let inline (|??) a b = nullCoalesceHelper<NullCoalesce, _, _, _> a b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment