Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment to Nullable in F#

Tags:

f#

I'm working with a library (WPF extended toolkit) where almost every property is a Nullable<'T>. This makes it something of a pain everywhere to constantly have to write

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

In C# this would convert implicitly. Is there any way to mimic the same behavior in F#? The most succinct option I've found is

checkbox.IsChecked <- unbox true

but that seems to generate more overhead in a tight loop (micro-optimization, but still), and even still it's less succinct than C#.

like image 832
Dax Fohl Avatar asked Dec 02 '22 19:12

Dax Fohl


2 Answers

The new keyword is optional, and type inference will take care of the generic argument:

open System
checkbox.IsChecked <- Nullable true

If you prefer not to type ten extra keystrokes each time, you can declare a function as Carsten König described, but the declaration need not be as verbose as his:

let nl x = Nullable x
checkbox.IsChecked <- nl true
like image 157
phoog Avatar answered Jan 08 '23 08:01

phoog


have a look at this question: Nullablle<>'s 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;
like image 41
Random Dev Avatar answered Jan 08 '23 08:01

Random Dev