While browsing StackOverflow I stumbled upon the following answer:
https://stackoverflow.com/a/3817367/162694
// ... removed unneeded code
/// This type is intended for private use within Singleton only.
type private SyncRoot = class end
type Singleton =
[<DefaultValue>]
static val mutable private instance: Singleton
private new() = { }
static member Instance =
lock typeof<SyncRoot> (fun() ->
// vvv
if box Singleton.instance = null then
// ^^^
Singleton.instance <- Singleton())
Singleton.instance
Can somebody elaborate why the box
here is needed?
The given Singleton
type doesn't have null
as a proper value. In other words, it's not nullable and normally shouldn't have the value null
. Hence, it is not sensible to compare a value of type Singleton
with null
, even though the use of an uninitialized variable via [<DefaultValue>]
may create a null-valued variable of this type. Boxing turns anything into obj
, which is nullable and therefore valid in this context.
Using Unchecked.defaultof<Singleton>
instead of null
would make the boxing unnecessary and compile. (There's also the [<AllowNullLiteral>]
attribute, which can be added to the Singleton
type to specify that instances of this type can be null
.)
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