Converting Enum to Base Type

I have an listing as follows

type Suit = |Clubs = 'C' |Spades = 'S' |Hearts = 'H' |Diamonds = 'D' 

How to get base char value if enum is given? for example, I'm Suit.Clubs and want to get 'C'

+6
source share
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 

Editorial: 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 
+11
source

You can use the 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 did not see these functions in my first attempt at an answer, so I suggested using first:

 unbox<char> Suit.Clubs 

This is less than what ildjarn suggests in the comment, but it has the same problem - there is no verification that you are actually converting to the correct type. With EnumToValue you cannot make this error because it always returns the value of the right base type.

+4
source

Source: https://habr.com/ru/post/907272/


All Articles