Reputation: 9835
Lets say I have the following type:
type BinaryOp =
{ Lhs: int
Rhs: int
Destination: int }
Is there a F# way of counting the members of that record, i.e. countMembers<BinaryOp> = 3
? I know I could use System.Reflection
but I'd rather not.
Upvotes: 4
Views: 73
Reputation: 243061
I do not think there is a way to do this without relying on the .NET reflection mechanism. However, the core F# library provides a convenient API on top of the .NET reflection for working with F# types. You can implement countMembers
using the F# reflection API like this:
open Microsoft.FSharp.Reflection
let countMembers<'T> =
FSharpType.GetRecordFields(typeof<'T>).Length
I'm not sure why you want to do this, or why you want to avoid reflection - maybe there is a completely diferent design for what you actually want to achieve - but if you need to count the number of fields in a record, this is the best way.
Upvotes: 5