Skip to content

Instantly share code, notes, and snippets.

@bmitc
Created June 19, 2021 05:13
Show Gist options
  • Save bmitc/c3bf27dbff8fe057db16dfaa2a71d28f to your computer and use it in GitHub Desktop.
Save bmitc/c3bf27dbff8fe057db16dfaa2a71d28f to your computer and use it in GitHub Desktop.
Convert discriminated union values to and from strings
open Microsoft.FSharp.Reflection
let toString (x: 'T) =
match FSharpValue.GetUnionFields(x, typeof<'T>) with
| case, _ -> case.Name
let fromString<'T> (s: string) =
match FSharpType.GetUnionCases typeof<'T> |> Array.filter (fun case -> case.Name = s) with
| [|case|] -> Some(FSharpValue.MakeUnion(case, [||]) :?> 'T)
| _ -> None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment