I'm calling functions in the XNA framework from F# that accept Nullable values. Now, in C#, you would just call:
foo(arg1, arg2, null, arg4)
Now, I tried that in F#, but it doesn't like it. It says: "Error 9 Type constraint mismatch. The type 'a is not compatible with type System.Nullable The type 'System.Nullable' does not have 'null' as a proper value."
I understand why this is happening, sort of, but it seems really inconvenient. All I'm doing now is, to make life easier, instead of repeatedly typing (Nullable<Rectangle>)null
everytime I call the function, I just did let nullRect = (Nullable<Rectangle>)null
, and use nullRect. This seems really stupid, especially since I'd have to do that for every nullable type I interact with. Is there a better, more idiomatic way to handle this?
Here's what I'd do:
[<GeneralizableValue>]
let nl<'a when 'a : struct
and 'a : (new : unit -> 'a)
and 'a :> System.ValueType> : System.Nullable<'a> =
unbox null
Now you can use nl
wherever you would have used null
before.
EDIT
As Tomas notes, this can be written much more concisely as:
let nl = System.Nullable<_>()
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