I have an enum as follows
type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'
How do I get the underlying char value if given enum value?
eg I have Suit.Clubs
and want to get 'C'
as another option
type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'
let c = Suit.Clubs
let v : char = LanguagePrimitives.EnumToValue c
EDITED: Comparison of different approaches:
type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'
let valueOf1 (e : Suit) = LanguagePrimitives.EnumToValue e
let valueOf2 (e : Suit) = unbox<char> e
let valueOf3 (e : Suit) = (box e) :?> char
And under the hood:
.method public static
char valueOf1 (
valuetype Program/Suit e
) cil managed
{
// Method begins at RVA 0x2050
// Code size 3 (0x3)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ret
} // end of method Program::valueOf1
.method public static
char valueOf2 (
valuetype Program/Suit e
) cil managed
{
// Method begins at RVA 0x2054
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box Program/Suit
IL_0007: unbox.any [mscorlib]System.Char
IL_000c: ret
} // end of method Program::valueOf2
.method public static
char valueOf3 (
valuetype Program/Suit e
) cil managed
{
// Method begins at RVA 0x2064
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box Program/Suit
IL_0007: unbox.any [mscorlib]System.Char
IL_000c: ret
} // end of method Program::valueOf3
You can use functions from the LanguagePrimitives
module:
// Convert enum value to the underlying char value
let ch = LanguagePrimitives.EnumToValue Suit.Clubs
// Convert the char value back to enum
let suit = LanguagePrimitives.EnumOfValue ch
EDIT: I didn't see these functions in my first answer attempt, so I first suggested using:
unbox<char> Suit.Clubs
This is shorter than what ildjarn suggests in a comment, but it has the same problem - there is no checking that you're actually converting to the right type. With EnumToValue
, you cannot make this mistake, because it always returns the value of the right underlying type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With