Nullable assignment in F #

I am working with a library (advanced WPF toolkit) where almost every property is Nullable<'T>

. It makes it something of a pain all over the world to write constantly

checkbox.IsChecked <- new Nullable<bool>(true)

      

In C # this will convert implicitly. Is there a way to simulate this same behavior in F #? The most concise option I've found is

checkbox.IsChecked <- unbox true

      

but this seems to create additional overhead in a tight loop (micro-optimization, but still) and even less concise than C #.

+3


source to share


3 answers


One fix is ​​to define a prefix operator:

let inline (!) (x: ^a) = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x)

checkbox.IsChecked <- !true

      



Be aware that this will obscure the de-reference operator. If this is a problem, you can choose a different symbol.

+3


source


The keyword new

is optional and the type inference will contain a generic argument:

open System
checkbox.IsChecked <- Nullable true

      



If you prefer not to type ten extra keystrokes each time, you can declare the function described by Carsten König, but the declaration does not have to be as detailed as his:

let nl x = Nullable x
checkbox.IsChecked <- nl true

      

+6


source


take a look at this question: Nullablle "and" null "in F # - you can do the same to wrap any value in a generic way:

let nl (x : 'a) = 
   System.Nullable<'a> (x)

      

and just use it like this:

checkbox.IsChecked <- nl true;

      

+5


source







All Articles