Search code examples
c#.netf#system.reflection

Detecting F# record type from C# at runtime


Is there a way to check if an object is an F# record type at runtime in C# without referencing the FSharp.Core library?


Solution

  • Record types get marked with [<CompilationMapping(SourceConstructFlags.RecordType)>] attribute at compilation. This is what FSharpType.IsRecord looks for, you can see the implementation here. Discriminated unions get marked in a similar way.

    It's possible to reimplement that logic without referring to any FSharp.Core types explicitly, i.e. you could look up the attribute by name and have your own copy of SourceConstructFlags enum for matching attribute data.