Learning F#, can't find the answer to this... I'd like to handle case where a Nullable parameter (DateTime? in the original c#) is null, but I get the error "Nullable does not have null as a proper value". What is the correct way to do this?
let addIfNotNull(ht:Hashtable, key:string, value:Nullable<DateTime>) =
match value with
| null -> ()
| _ -> ht.Add(key,value)
ht
From https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/nullable-operators:
The actual value can be obtained from a
System.Nullable<'T>
object by using theValue
property, and you can determine if aSystem.Nullable<'T>
object has a value by calling theHasValue
method.
So instead of the match
you do
if value.HasValue then ht.Add(key, value.Value)
You could use
match Option.ofNullable value with ...
or declare some active patterns to help.
While @AlexeyRomanov's answer is perfectly valid, if you really want to match over a Nullable
value, you can define an Active Pattern like so:
let (|Null|Value|) (x : _ Nullable) =
if x.HasValue then Value x.Value else Null
And then use it in your function:
let addIfNotNull (ht : Hashtable) (key : string)
(value : Nullable<DateTime>) =
match value with
| Null -> ()
| Value dt -> ht.Add (key, dt)
ht
I took the liberty to change your function's signature so it takes curried parameters; unless you have specific requirements, curried parameters are usually preferred over tupled parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With