Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@piers7
Created October 21, 2016 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piers7/8aeb8350453c0cd110d5e7a3e019cc86 to your computer and use it in GitHub Desktop.
Save piers7/8aeb8350453c0cd110d5e7a3e019cc86 to your computer and use it in GitHub Desktop.
Smartly unboxes a value from a data reader into various target representations
/// Smartly unboxes a nullable value, with different semantics depending on the target type (nullable, option etc...)
let SmartUnbox<'a> isNull (value:obj) : 'a =
// help from from http://www.fssnip.net/hh
let targetType = typeof<'a>
let typeFlavour = TypeFlavour.Create<'a>()
match (isNull,typeFlavour) with
| true, ValueType -> failwithf "Can't return null for type %s" targetType.Name
| true, _ -> (box null) :?> 'a // cast null to nullable/option/reference type works fine!
| false, OptionT t ->
// Have to create the 'Some' member via reflection
targetType.GetMethod("Some").Invoke(null, [| value |]) :?> 'a
| false, _ -> value |> unbox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment