mercredi 22 août 2018

How do I create an instance of an F# option type using Activator.CreateInstance?

I can create a function to create an option type based on any type:

let createOptionType typeParam =
    typeof<unit option>.GetGenericTypeDefinition().MakeGenericType([| typeParam |])

...and I can confirm that the function works:

createOptionType (typeof<int>) = (Some 5).GetType() // returns true

...and I can create the value "Some 0" by doing this:

System.Activator.CreateInstance(x.GetType(), [| null |]) // returns Some 0

However, I don't know how to create any other "Some x" value, or how to create "None". (It appears that it creates "Some ", because for strings it's "Some null".)





Aucun commentaire:

Enregistrer un commentaire