Chapter 6. Discriminated Unions

Discriminated unions (DUs) are a way of defining a type (or class in the OOP world) that is actually one of a set of different types. Which type an instance of a DU actually is at any given moment has to be checked before use.

F# has DUs available natively, and it’s a feature used extensively by F# developers. Despite sharing a common runtime with C#, and the feature being there for us in theory, there are only plans in place to introduce them into C# at some point, but it’s not certain how or when. In the meantime, we can roughly simulate them with abstract classes, and that’s the technique I’m going to talk about in this chapter.

This chapter is our first dabble into some of the more advanced areas of FP. Earlier chapters were more focused on how you, the developer, can work smart, not hard. We’ve also looked at ways to reduce boilerplate and to make code more robust and maintainable.

DUs are a programming structure that will do all of this too,1 but are more than a simple extension method, or a single-line fix to remove a little bit of boilerplate. DUs are closer in concept to a design pattern—in that they have a structure and some logic that needs to be implemented around it.

Holiday Time

Let’s imagine an old-school object-oriented problem of creating a system for package holidays (or vacations in the US). You know, the sort where the travel agency arranges a customer’s travel and accommodations, all in one. I’ll leave you to imagine which ...

Get Functional Programming with C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.