Skip to content

Instantly share code, notes, and snippets.

@suside
suside / UnionStringSerializer.fs
Created May 12, 2023 06:36
Union serialization provider for F#
let UnionToString (u: 'a) =
match FSharpValue.GetUnionFields(u, typeof<'a>) with
| case, _ -> case.Name
let StringToUnion<'a> (s: string) =
match FSharpType.GetUnionCases typeof<'a> |> Array.filter (fun case -> case.Name = s) with
| [| case |] -> FSharpValue.MakeUnion(case, [||]) :?> 'a
| _ -> failwithf "Unable to parse %A" s
type UnionStringSerializer<'a>() =