How to enumerate a discriminated union in F#?

Yes, F# has it’s own reflection layer build on top of .NET’s reflection to help you make sense of types that are specific to F#, like discriminating unions. Here’s the code that will let you enumerate a union’s cases:

open Microsoft.FSharp.Reflection

type MyDU =
    | One
    | Two
    | Three

let cases = FSharpType.GetUnionCases typeof<MyDU>

for case in cases do printfn "%s" case.Name

Leave a Comment