Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get Record fields by string in F#?

Tags:

f#

I would like to get the value of a field in a Record by looking it up with a string.

type Test = { example : string  }
let test = { example = "this is the value" }
let getByName (s:string) =
  ???? //something like test.GetByName(s)
like image 525
Istvan Avatar asked Oct 20 '25 04:10

Istvan


1 Answers

Standard .net reflection should be working fine for such scenario. Record fields are exposed as properties, so you can just query the type with reflection API. It could look like this:

  let getByName (s:string) =
    match typeof<Test>.GetProperties() |> Array.tryFind (fun t -> t.Name = s)
      with
      | Some pi -> Some(pi.GetValue(test))
      | None -> None
like image 189
3615 Avatar answered Oct 21 '25 22:10

3615



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!