How to check enumerator value with [Flags]?

3

I have my enumerator:

[Flags]
public enum EConta {
   Receber = 1,
   Pagar = 2,
   Cobrada = 3,
   Atrazada = 4
}

and I have the assignment

EConta conta = EConta.Receber | EConta.Pagar;
var retorno = EConta.Cobrada

How do I compare if the variable conta has the value of the variable retorno ?

I tested it like this:

conta.HasFlag(retorno)

There is no error, but it does not work

What's wrong?

    
asked by anonymous 21.04.2015 / 16:06

1 answer

4

In order for the HasFlag method to work as expected, enum should simulate the representation of a byte in bits >. Each element of enum should have a value corresponding to 2 ^ n where n is its position in the byte in binary representation.

You'll need to change your enum to:

[Flags]
public enum EConta {
   none = 0,
   Receber = 1,
   Pagar = 2,
   Cobrada = 4,
   Atrazada = 8
}
    
21.04.2015 / 16:14