Anonymous records

Introduction

  • Since Fβ™― 4.6 (March 2019)

  • Syntax: same as Record with "fat" braces {| fields |}

    • {| Age: int |} β†’ signature

    • {| Age = 15 |} β†’ instance

  • Inline typing: no need to pre-define a named type

    • Alternative to Tuples

  • Allowed in function input/output

    • β‰  Anonymous type Cβ™―

Benefits βœ…

  • Reduce boilerplate

  • Improve interop with external systems (JavaScript, SQL...)

  • Compatible with Cβ™― anonymous types: β†’ When a Cβ™― API requires an anonymous type, we can give it an anonymous record instance.

Examples (more on this later) :

  • LINQ projection

  • Customization of an existing record

  • JSON serialization

  • Inline signature

  • Alias by module

LINQ Projection

πŸ’‘ Select a subset of properties

In Cβ™―, we would use an anonymous type:

πŸ”— F# vs C#: Anonymous Records by Krzysztof Kraszewski

Customize an existing record

πŸ’‘ An anonymous record can be instantiated from a record instance

JSON serialization

πŸ’‘ An anonymous record can be used as an intermediary type to serialize a union in JSON.

Example:

Resulting JSON:

β†’ Format verbose and not practical.

πŸ’‘ Solution: Define an anonymous record as "DTO" to serialize a customer.

Resulting JSON:

Signature inline

πŸ’‘ Use an anonymous record declared inside a bigger type to reduce cognitive load:

Limits πŸ›‘

Last updated

Was this helpful?