Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# Cast enum element type

Tags:

enums

f#

I have a question rather simple I think but I can not find any info about it. So for example in c# I can define value enum types using inheritance like:

public enum RequestedService : ushort
{
    [Description("Unknown")]
    Unknown = 0,

    [Description("Status")]
    SERVICE1 = 0x0001
}

But how would I do it in F#, so far I translate it like:

type RequestedService =
    | [<Description("Unknown")>] Unknown = 0u
    | [<Description("Status")>] SERVICE1 = 0x0001u

I tried using inheritance, and tried to define type before value like

Unknown = uint16 0u

But I am getting compile error, so is it possible?

like image 335
Wojciech Szabowicz Avatar asked Nov 15 '25 16:11

Wojciech Szabowicz


1 Answers

Casting of non-int32 values to an enum is documented in Enumerations:

The default enum function works with type int32. Therefore, it cannot be used with enumeration types that have other underlying types. Instead, use the following.

type uColor =
   | Red = 0u
   | Green = 1u
   | Blue = 2u
let col3 = Microsoft.FSharp.Core.LanguagePrimitives.EnumOfValue<uint32, uColor>(2u)

Thus you would do:

open Microsoft.FSharp.Core.LanguagePrimitives

type RequestedService =
    | [<Description("Unknown")>] Unknown = 0u
    | [<Description("Status")>] SERVICE1 = 0x0001u

let service = EnumOfValue<uint32, RequestedService>(0u) // Or 1u or whatever

Or if you prefer:

let service : RequestedService = EnumOfValue 0u // Or 1u or whatever

For more see: LanguagePrimitives.EnumOfValue<'T,'Enum> Function.

like image 195
dbc Avatar answered Nov 18 '25 21:11

dbc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!