Search code examples
f#discriminated-union

Enumerate names and values of an F# Discriminated Union type like Enum.GetValues


First, I read this: How to enumerate a discriminated union in F#? but it doesn't really solve my issue.

I am trying to parse a discriminated union, get all the types, get their names and then put them in a dictionary (well, more than that but it's to simplify the example)

open Microsoft.FSharp.Reflection

type MyDU =
|TypeA
|TypeB

let l = Dictionary<MyDU, string>()    

FSharpType.GetUnionCases typeof<ExchangeList>
|> Seq.iter (fun x ->
    l.[WHAT DO I PUT HERE?] <- x.Name
)

I don't know, from the UnionCaseInfo how to get the actual type to put as a key in my dictionary.

Before, I had an enum, so it was simpler:

Enum.GetValues(typeof<MyEnum>)
|> unbox
|> Seq.iter (fun x ->
    l.[x] <- string x

Solution

  • You can create an instance of a DU using F# reflection using the FSharpValue.MakeUnion function:

    for x in FSharpType.GetUnionCases typeof<MyDU> do
      l.[FSharpValue.MakeUnion(x, [||]) :?> MyDU] <- x.Name