Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Enum into underlying type

Tags:

f#

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'

like image 444
Jason Quinn Avatar asked Jan 30 '12 23:01

Jason Quinn


2 Answers

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
like image 94
desco Avatar answered Oct 18 '22 05:10

desco


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.

like image 7
Tomas Petricek Avatar answered Oct 18 '22 04:10

Tomas Petricek