Home > database >  how to specify an underlying type for enum in F#
how to specify an underlying type for enum in F#

Time:01-15

We can specify an underlying type for enum in C# like this:

[Flags]
public enum MyKinds : ushort
{
    None  = 0,
    Flag1 = 1 << 0,
    Flag2 = 1 << 1,
    // ...
}
  1. How can I do that using F# ?
type MyKinds = 
    | None  = 0 
    | Flag1 = 1
    | Flag2 = 2

    // inherit ushort  // error FS0912
  1. How can I define enum values using bitwise operator like 1 << 0 in F# ?
type MyKinds = 
    | None = 0 
    | Flag1 = 1 << 0    // error FS0010
    | Flag2 = 1 << 1    // error FS0010

CodePudding user response:

You can't use bit shifting, but isn't this even better?

type MyKinds = 
    | None =  0b0000us
    | Flag1 = 0b0001us
    | Flag2 = 0b0010us

Also, if these are to be used as bit flags, you might want to add the [<Flag>] attribute, so that printing the value will show any combination of flags.

CodePudding user response:

As specified in The Docs, the underlying type of an enum in F# is determined by the numerical suffix.
So in your case, for ushort (unit16), it would be:

type MyKinds = 
    | None  = 0us 
    | Flag1 = 1us
    | Flag2 = 2us

(suffixes for different number types available Here)

  •  Tags:  
  • Related