layout: post
title: “Enum types”
description: “Not the same as a union type”
nav: fsharp-types
seriesId: “Understanding F# types”
seriesOrder: 8

categories: [Types]

The enum type in F# is the same as the enum type in C#. Its definition is superficially just like that of a union type, but there are many non-obvious differences to be aware of.

Defining enums

To define an enum you use exactly the same syntax as a union type with empty cases, except that you must specify a constant value for each case, and the constants must all be of the same type.

  1. type SizeUnion = Small | Medium | Large // union
  2. type ColorEnum = Red=0 | Yellow=1 | Blue=2 // enum

Strings are not allowed, only ints or compatible types such bytes and chars:

  1. type MyEnum = Yes = "Y" | No ="N" // Error. Strings not allowed.
  2. type MyEnum = Yes = 'Y' | No ='N' // Ok because char was used.

Union types require that their cases start with an uppercase letter. This is not required for enums.

  1. type SizeUnion = Small | Medium | large // Error - "large" is invalid.
  2. type ColorEnum = Red=0 | Yellow=1 | blue=2 // Ok

Just as with C#, you can use the FlagsAttribute for bit flags:

  1. [<System.FlagsAttribute>]
  2. type PermissionFlags = Read = 1 | Write = 2 | Execute = 4
  3. let permission = PermissionFlags.Read ||| PermissionFlags.Write

Constructing enums

Unlike union types, to construct an enum you must always use a qualified name:

  1. let red = Red // Error. Enums must be qualified
  2. let red = ColorEnum.Red // Ok
  3. let small = Small // Ok. Unions do not need to be qualified

You can also cast to and from the underlying int type:

  1. let redInt = int ColorEnum.Red
  2. let redAgain:ColorEnum = enum redInt // cast to a specified enum type
  3. let yellowAgain = enum<ColorEnum>(1) // or create directly

You can even create values that are not on the enumerated list at all.

  1. let unknownColor = enum<ColorEnum>(99) // valid

And, unlike unions, you can use the BCL Enum functions to enumerate and parse values, just as with C#. For example:

  1. let values = System.Enum.GetValues(typeof<ColorEnum>)
  2. let redFromString =
  3. System.Enum.Parse(typeof<ColorEnum>,"Red")
  4. :?> ColorEnum // downcast needed

Matching enums

To match an enum you must again always use a qualified name:

  1. let unqualifiedMatch x =
  2. match x with
  3. | Red -> printfn "red" // warning FS0049
  4. | _ -> printfn "something else"
  5. let qualifiedMatch x =
  6. match x with
  7. | ColorEnum.Red -> printfn "red" //OK. qualified name used.
  8. | _ -> printfn "something else"

Both unions and enums will warn if you have not covered all known cases when pattern matching:

  1. let matchUnionIncomplete x =
  2. match x with
  3. | Small -> printfn "small"
  4. | Medium -> printfn "medium"
  5. // Warning: Incomplete pattern matches
  6. let matchEnumIncomplete x =
  7. match x with
  8. | ColorEnum.Red -> printfn "red"
  9. | ColorEnum.Yellow -> printfn "yellow"
  10. // Warning: Incomplete pattern matches

One important difference between unions and enums is that can you make the compiler happy about exhaustive pattern matching by listing all the union types.

Not so for enums. It is possible to create an enum not on the predeclared list, and try to match with it, and get a runtime exception, so the compiler will warn you even if you have explicitly
listed all the known enums:

  1. // the compiler is still not happy
  2. let matchEnumIncomplete2 x =
  3. match x with
  4. | ColorEnum.Red -> printfn "red"
  5. | ColorEnum.Yellow -> printfn "yellow"
  6. | ColorEnum.Blue -> printfn "blue"
  7. // the value '3' may indicate a case not covered by the pattern(s).

The only way to fix this is to add a wildcard to the bottom of the cases, to handle enums outside the predeclared range.

  1. // the compiler is finally happy
  2. let matchEnumComplete x =
  3. match x with
  4. | ColorEnum.Red -> printfn "red"
  5. | ColorEnum.Yellow -> printfn "yellow"
  6. | ColorEnum.Blue -> printfn "blue"
  7. | _ -> printfn "something else"
  8. // test with unknown case
  9. let unknownColor = enum<ColorEnum>(99) // valid
  10. matchEnumComplete unknownColor

Summary

In general, you should prefer discriminated union types over enums, unless you really need to have an int value associated with them,
or you are writing types that need to be exposed to other .NET languages.