Reputation: 21755
Let's consider the following enum in C#
public enum ScrollMode : byte
{
None = 0,
Left = 1,
Right = 2,
Up = 3,
Down = 4
}
The F# code receives a byte and has to return an instance of the enum I have tried
let mode = 1uy
let x = (ScrollMode)mode
(Of course in the real application I do not get to set 'mode', it is received as part of network data).
The example above does not compile, any suggestions?
Upvotes: 14
Views: 3920
Reputation: 118865
For enums whose underlying type is 'int', the 'enum' function will do the conversion, but for non-int enums, you need 'LanguagePrimitives.EnumOfValue', a la:
// define an enumerated type with an sbyte implementation
type EnumType =
| Zero = 0y
| Ten = 10y
// examples to convert to and from
let x = sbyte EnumType.Zero
let y : EnumType = LanguagePrimitives.EnumOfValue 10y
(EnumOfValue is listed here
(now http://msdn.microsoft.com/en-us/library/ee340276(VS.100).aspx )
whereas enum is listed here
(now http://msdn.microsoft.com/en-us/library/ee353754(VS.100).aspx ) )
Upvotes: 22