Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9040357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T09:57:54+00:00 2026-06-16T09:57:54+00:00

I am enumerating through values in some discriminated unions in F# using reflection (e.g.

  • 0

I am enumerating through values in some discriminated unions in F# using reflection (e.g. How to enumerate a discriminated union in F#?). I want to use the values that I got from using reflection in generating different record types that are composed from the discriminated unions that I am enumerating through but I am unsure of how to cast the type UnionCaseInfo to an actual union case. Is it possible to perform such a cast? The code below represents exactly what I am trying to do (the values in the discriminated union are different and so are the variable names). I am aware I could use enumeration but I would prefer to not to use them instead of discriminated unions.

open System
open Microsoft.FSharp.Collections
open Microsoft.FSharp.Reflection

let GetUnionCaseName (x:'a) = 
    match FSharpValue.GetUnionFields(x, typeof<'a>) with
    | case, _ -> case.Name  

type shape =
    | Square
    | Circle
    | Triangle
    | Other

type color =
    | Black
    | Red
    | Blue
    | Green
    | White

type coloredShape = { Shape: shape; Color: color }

let shapeCases = FSharpType.GetUnionCases typeof<shape>
let colorCases = FSharpType.GetUnionCases typeof<color>

let boardOfRelevantPossibilities = Microsoft.FSharp.Collections.Array2D.init<coloredShape> 5 3 (fun x y -> {Shape = Other; Color = Black})

let OtherShape = GetUnionCaseName(shape.Other)
let rand = Random()

for shapeCase in shapeCases do
    // Is there a way to do the following comparison this without using string comparisons
    if not (shapeCase.Name.Equals OtherShape) then
        for colorCase in colorCases do
            let mutable addedToBoard = false

            while not addedToBoard do
                let boardRowIndex = rand.Next(0,4)
                let boardColumnIndex = rand.Next(0,2)

                if boardOfRelevantPossibilities.[boardRowIndex,boardColumnIndex].Shape.Equals shape.Other then
                    addedToBoard <- true

                    // I want to utilize colorCase instead of other and shapeCase instead of black
                    boardOfRelevantPossibilities.[boardRowIndex,boardColumnIndex] <- {Shape = Other; // Shape should be determined by shapeCase instead of Other  
                        Color = White } // Color should be determined by colorCase instead of White

Console.ReadKey() |> ignore

I re-re-factored my code to the following:

open System
open Microsoft.FSharp.Collections
open Microsoft.FSharp.Reflection

let allUnionCases<'T>() =
    FSharpType.GetUnionCases(typeof<'T>)
    |> Array.map (fun case -> FSharpValue.MakeUnion(case, [||]) :?> 'T)

type shape =
    | Square
    | Circle
    | Triangle
    | Other

type color =
    | Black
    | Red
    | Blue
    | Green
    | White

type coloredShape = { Shape: shape; Color: color }

let shapeCases = FSharpType.GetUnionCases typeof<shape>
let colorCases = FSharpType.GetUnionCases typeof<color>

let numberOfRows = 5
let numberOfColumns = 3
let boardOfRelevantPossibilities = Microsoft.FSharp.Collections.Array2D.init<coloredShape> numberOfRows numberOfColumns (fun x y -> {Shape = Other; Color = Black})

let rand = Random()

for shapeCase in allUnionCases<shape>() do
    // No string comparison anymore
    if shapeCase <> shape.Other then
        for colorCase in allUnionCases<color>() do
            let mutable addedToBoard = false

            while not addedToBoard do
                let boardRowIndex = rand.Next(0,numberOfRows)
                let boardColumnIndex = rand.Next(0,numberOfColumns)

                if boardOfRelevantPossibilities.[boardRowIndex,boardColumnIndex].Shape.Equals shape.Other then
                    addedToBoard <- true
                    // utilizing colorCase and shapeCase to create records to fill array
                    boardOfRelevantPossibilities.[boardRowIndex,boardColumnIndex] <- {Shape = shapeCase; Color = colorCase } 


printfn "%A" boardOfRelevantPossibilities
Console.ReadKey() |> ignore

This new re-factoring incorporates reflection to enumerate through discriminated unions while allowing me to generate different record types composed of those discriminated unions. I also caught two off-by-one errors, they are fixed in the re-factored code.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T09:57:55+00:00Added an answer on June 16, 2026 at 9:57 am

    To be honest, I prefer to enumerate all union cases manually in a static method rather than create them through reflection.

    As @John said, you need one more step using FSharpValue.MakeUnion:

    let allUnionCases<'T>() =
        FSharpType.GetUnionCases(typeof<'T>)
        |> Array.map (fun case -> FSharpValue.MakeUnion(case, [||]) :?> 'T)
    

    In the while loop, you should use = instead of Equals and use union cases (shape.Other) without fully-qualified names.

    /// Use type params for clarity; type inference should work fine without them
    for shapeCase in allUnionCases<shape>() do
        for colorCase in allUnionCases<color>() do
            let mutable addedToBoard = false
            while not addedToBoard do
                let r = rand.Next(0,4)
                let c = rand.Next(0,2)
                if boardOfRelevantPossibilities.[r, c].Shape = Other then
                    addedToBoard <- true
                    boardOfRelevantPossibilities.[r, c] <- { Shape = shapeCase; 
                                                             Color = colorCase } 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Enumerating through an object's properties (string) in C# Can I use reflection
I have a table that i am enumerating through my model with. I have
I'm stumped. I have an NSMutableDictionary w/ nested dictionaries that I am enumerating through
I have an enumeration of values that come through an API. Those names are
I have a series of images that I want to make use of in
Possible Duplicate: Modifying .NET Dictionary while Enumerating through it I have a dictionary object
I'm enumerating all databases of an SQL Server 2005 instance using SMO like as
I'm having some problems with encapsulation in C#. There are two specific scenarios that
I need to create several combo boxes to represent enumeration values. I want the
I'm creating an options dialog using WPF that lists possible keys so that the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.