Lesson 10. Shaping data with records

 

In the previous lesson, you looked at a lightweight, simple way of packaging data pieces together with the tuple. You also saw that tuples are great in some situations, but in others not so much. Now you’ll look at F#’s secondary data structure: the record, a more fully featured data structure more akin to a class. In this lesson

  • You’ll see what records are within F#.
  • You’ll understand how records compare with C# and VB classes.
  • You’ll learn how to affect changes to records while still retaining immutability.
  • You’ll see tips for working with records.

Let’s start by continuing where we left off in the previous lesson and by describing a situation where tuples aren’t suitable for exposing data. For example, a tuple wouldn’t be suitable for a public contract of some sort where you want explicit named fields, or somewhere that you need to expose more than two or three properties. Here’s a simple example of a Customer type in C#.

Listing 10.1. A basic DTO in C#
public class Customer {                       #1
    public string Forename { get; set; }      #2
    public string Surname { get; set; }
    public int Age { get; set; }
    public Address Address { get; set; }
    public string EmailAddress { get; set; }
}

10.1. POCOs done right: records in F#

10.2. Doing more with records

10.3. Tips and tricks with records

Summary

sitemap