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?
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
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.LanguagePrimitives.html
(now http://msdn.microsoft.com/en-us/library/ee340276(VS.100).aspx )
whereas enum is listed here
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html
(now http://msdn.microsoft.com/en-us/library/ee353754(VS.100).aspx ) )
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