Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if an Enum value has one or more of the values it's being compared with?

Tags:

c#

enums

flags

I've got an Enum marked with the [Flags] attribute as follows:

[Flags]
public enum Tag : int
{
    None = 0,
    PrimaryNav = 1,
    HideChildPages = 2,
    HomePage = 4,
    FooterLink = 8
}

On sitemapnodes in my sitemap I store the int value for the tags combination as an attribute.

What I need to do is check if a node has any one of one or more tags, e.g. Tag.PrimaryNav | Tag.HomePage.

I'm struggling with the necessary boolean logic to determine if an Enum value has one or more of the values it's being compared with.

Apologies if this isn't clear. I can provide more information if necessary.

like image 914
Paul Suart Avatar asked Mar 09 '10 12:03

Paul Suart


2 Answers

You can use the HasFlag Method to avoid the need for the boolean logic,

Tag Val = (Tag)9;

if (Val.HasFlag(Tag.PrimaryNav))
{
    Console.WriteLine("Primary Nav");
}

if(Val.HasFlag(Tag.HomePage))
{
    Console.WriteLine("Home Page");
}
like image 28
rerun Avatar answered Oct 19 '22 23:10

rerun


You can do that by combining values with | and checking via &.

To check if the value contains either of the tags:

if ((myValue & (Tag.PrimaryNav | Tag.HomePage)) != 0) { ... }

The | combines the enums you're testing (bitwise) and the & tests via bitwise masking -- if the result isn't zero, it has at least one of them set.

If you want to test whether it has both of them set, you can do that as well:

Tag desiredValue = Tag.PrimaryNav | Tag.HomePage;
if ((myValue & desiredValue) == desiredValue) { ... }

Here we're masking off anything we don't care about, and testing that the resulting value equals what we do care about (we can't use != 0 like before because that would match either value and here we're interested in both).

Some links:

  • The & Operator
  • The | Operator
like image 147
T.J. Crowder Avatar answered Oct 20 '22 00:10

T.J. Crowder