Enums

β†’ Real .NET enum!

Declaration

Set of integer constants (byte, int...)

type ColorN =
    | Red   = 1
    | Green = 2
    | Blue  = 3

☝️ Note the syntax difference with a enum-like union:

type Color = Red | Green | Blue

Underlying type

  • Unlike Cβ™―, there is no default underlying type in Fβ™―.

  • The underlying type is defined by means of literals defining member values:

    • 1, 2, 3 β†’ int

    • 1uy, 2uy, 3uy β†’ byte

    • Etc. - see Literals

Corollary: you must use the same type for all members, otherwise it won't compile!

Char

char type can be used as the underlying type, but not the string:

Member naming

Enum members can be in camelCase:

Usages

⚠️ Unlike unions, the use of an enum literal is necessarily qualified

πŸ’‘ We can force the qualification for union types too:

Conversion

Pattern matching

⚠️ Unlike unions, pattern matching on enums is not exhaustive β†’ See Warning FS0104: Enums may take values outside known cases...

Flags

Same principle as in Cβ™―:

πŸ’‘ Note the ||| operator called "binary OR" (same as | in Cβ™―)

πŸ’‘ Hint: use binary notation for flag values:

Values

System.Enum.GetValues() returns the list of members of an enum ⚠️ Weakly typed: Array (non-generic array) πŸ’‘ Use a helper like:

Enum vs Union

Type
Data inside
Qualification
Exhaustivity

Enum

integers

Required

❌ No

Union

any

Optional

βœ… Yes

☝ Recommendation:

  • Prefer Union over Enum in most cases

  • Choose an Enum for:

    • .NET Interop

    • int data

    • Flags feature

Extras

πŸ’‘ NuGet package FSharpx.Extras β†’ Includes an Enum module with these helpers:

  • parse<'enum>: string -> 'enum

  • tryParse<'enum>: string -> 'enum option

  • getValues<'enum>: unit -> 'enum seq

Last updated

Was this helpful?