How to check value in enumerator with [Flags]?

Asked

Viewed 63 times

3

I have my enumerator:

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

and have the assignment

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

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

I tested it like this:

conta.HasFlag(retorno)

No error happens, but it doesn’t work

What’s wrong with it ?

1 answer

4


So that the method Hasflag function as expected or Enum shall simulate the representation of a byte in bits. Each element of Enum shall have a value corresponding to 2 n where n is its position in the byte in binary representation.

You will need to change your Enum to:

[Flags]
public enum EConta {
   none = 0,
   Receber = 1,
   Pagar = 2,
   Cobrada = 4,
   Atrazada = 8
}
  • thanks for the answer, and if I need to have another value on Enum, the value will be 16 ? that ?

  • Yes 16, 32, 64 etc, .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.