Tuesday, December 29, 2009

Enum with binary comparison (bitwise AND operation)

Below is an example on how to compare values using binary with enum type.

1) Declare enum variable with specified binary values.

enum status
{
Adding = 0x1, Modifying = 0x2, Deleting = 0x4, Modified = 0x8, Deleted = 0x16
};


2. Create an new instance of enum with explicit values using "|" or a bitwise OR operation.

status newStatus = status.Modified | status.Deleted;

3. Now using binary comparison using bitwise AND operation to check if enum value was included with the new instance created.

bool ifExists = ((newStatus & status.Modifying) == status.Modifying);

The code example above returns false since "Modifying" was not declared in newStatus enum.

No comments:

Post a Comment