0

I have an enum of bit-masked error codes with a string representation and an binary int representation:

type ErrorCodes = 
    | NoError = 0
    | InvalidInputError = 1
    | AuthenticationFailedError = 2
    | InvalidArgumentError = 4
    | ItemNotFoundError = 8
    | UnknownError = 16

As I run through the program, I collect all the errors by using the bitwise OR operator (|||). So now I have something that looks like 01100. How can I print to the console: "InvalidArgumentError", and "ItemNotFoundError?"

I had an idea of just using:

for i = 0 to 32 do
    if ((err.GetHashCode() % 2) = 1) then
        Console.WriteLine("ErrorCode: {0}",err.GetHashCode())

But now I'm stuck on how to print the actual string

user3685285
  • 6,066
  • 13
  • 54
  • 95

2 Answers2

5

If you decorate your ErrorCodes type with the System.Flags attribute then .ToString will format as a list of value names.

[<System.Flags>]
type ErrorCodes = ...

let errors = ErrorCodes.InvalidInputError ||| ErrorCodes.UnknownError

printfn "%O" errors
Leaf Garland
  • 3,647
  • 18
  • 18
0

If, for whatever reason, you don't want the default flags ToString implementation, you could do something like this:

let inline printFlags (flags: 'e) =
    let ty = typeof<'e>
    (Enum.GetValues ty :?> 'e[], Enum.GetNames ty)
    ||> Array.zip
    |> Seq.filter (fun (v, _) -> v <> enum 0 && flags &&& v = v)
    |> Seq.iter (snd >> printfn "%s")

printFlags (ErrorCodes.InvalidInputError ||| ErrorCodes.UnknownError)

Output:

InvalidInputError
UnknownError
Daniel
  • 47,404
  • 11
  • 101
  • 179