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 | BlueUnderlying 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βint1uy,2uy,3uyβbyteEtc. - 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
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 -> 'enumtryParse<'enum>: string -> 'enum optiongetValues<'enum>: unit -> 'enum seq
Last updated
Was this helpful?