Validating Bit-Coded Enum Values

Question
What’s the recommended way to check bit-coded enum values?

Answer
The following code demonstrates how to test bit-coded enum values.

FileProperty fileProperty = GetFileProperties();

// Incorrect. This will fail if fileProperty has more than one bit set.
if ( fileProperty == FileProperty.Hidden ) {
    ...
}

// Also incorrect. This cannot test multiple bits at once.
if ( (fileProperty & FileProperty.Hidden ) != 0 ) {
    ...
}

// The correct way.
if ( (fileProperty & FileProperty.Hidden) == FileProperty.Hidden ) {
    ...
}

// An example that checks whether a file is System AND Hidden.
FileProperty property = FileProperty.System | FileProperty.Hidden;
if ( (fileProperty & property) == property ) {
    ...
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s