TimothyP
TimothyP

Reputation: 21755

Converting byte to an instance of an enum in F#

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

Answers (2)

Brian
Brian

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

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 ) )

Upvotes: 22

user202863
user202863

Reputation:

let x : ScrollMode = enum mode

Upvotes: 4

Related Questions