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?
Casting of non-int32 values to an enum is documented in Enumerations:
The default
enumfunction works with typeint32. 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.
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