Created
October 21, 2016 04:38
-
-
Save piers7/8aeb8350453c0cd110d5e7a3e019cc86 to your computer and use it in GitHub Desktop.
Smartly unboxes a value from a data reader into various target representations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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