Reputation: 694
I am trying to construct a record type in F#. But the following code is giving System.InvalidCastException
. I am new to F# and having a difficult time understanding as to why this isn't working. A detailed explanation would be much appreciated.
open System
open Microsoft.FSharp.Reflection
type Employee = {
Id: Guid
Name: string
Phone: string
BadgeId: string
Designation: string
}
let values =
[
"bc07e94c-b376-45a2-928b-508b888802c9"
"A"
"B"
"C"
"D"
]
|> Seq.ofList
let creator = FSharpValue.PreComputeRecordConstructor(typeof<Employee>, System.Reflection.BindingFlags.Public)
let x =
(
creator [|
values
|> Seq.map (fun y -> y)
|]
) :?> Employee
printfn "%A" x
Upvotes: 1
Views: 204
Reputation: 243041
There are two issues with your code. First, your record expects a value of type Guid
, but you are giving it a guid as a string. You can fix this by boxing everyting in your values
list:
let values =
[
box (Guid("bc07e94c-b376-45a2-928b-508b888802c9"))
box "A"
box "B"
box "C"
box "D"
]
The second issue is that you call creator
with an array containing a sequence as an argument (there is an extra wrapping). You need to give it array containing the values:
let emp = creator (Array.ofSeq values) :?> Employee
Upvotes: 3