0

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
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Thomas
  • 10,933
  • 14
  • 65
  • 136
  • This seems like a whole lot of trouble for something simple, it's probably much easier to have your DU given a static member that returns all its cases. But why do you need this in the first place? If any case has some fields, you won't be able to instantiate it anyway, at least not usefully. A DU is fundamentally different from an enum (the latter is a simple native int, while a DU is a box for various kinds of data). – Abel Jun 04 '20 at 15:21
  • The reason for this is that it is used in common code and I want to make sure that when types are added, code matching them will fail to compile (therefore the DU instead of an enum) for not covering all cases. But some data streams names are made using the 'enum' names, so I need to be able to iterate through them and extract the names. – Thomas Jun 04 '20 at 15:52
  • Sounds like you should use serialization and deserialization instead as a simpler solution. DU's are not meant for this kind of enumeration-of-the-type, but it's possible. – Abel Jun 05 '20 at 10:07

1 Answers1

2

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
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553