Saeed Neamati
Saeed Neamati

Reputation: 35852

How to use Flags attribute?

I have some items in database. Each of'em can have many tags, like Browsable, or IsInMenu and so on. A friend of mine suggested to use enums with Flags attribute to create an extensible solution. So, I created a field in DB which takes an integer value, then I created this enum:

 [Flags]
 public enum ItemTags { Browsable = 2, IsInMenu = 4}

Now I'd like to be able to semantically get the list of some items this way:

 public List<Item> GetItems(ItemTags tags)
 {
     /* 
     Code to get data from DB, something like, 
     return repository.GetList(tags);
     */
 }    

and in UI, I'd like to call:

 List<Item> items =  GetItems(ItemTags.Browsable | ItemTags.IsInMneu);

But I don't get the desired result. Am I going the right way? By desired result, I mean this: Values stored in database could be one of the 0, 2, 4, 6 values now. 0 means that the item is not in Menu and also not Browsable. 2 Means that item is Browable, but not in Menu. 4 means item is in Menu, but not Browsable. 6 means item is both Browsable and IsInMenu. Now when I call GetItems function, I don't get all the items which are browsable, in menu, or both browsable and in menu.

Upvotes: 0

Views: 5040

Answers (3)

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

use the FlagsAttribute Class

Indicates that an enumeration can be treated as a bit field; that is, a set of flags.

[Flags] 
public enum ItemTags 
{ 
  Default =0,
  Browsable = 2, 
  IsInMenu = 4,
  All = 6 // Browsable / IsInMenu
}

More here

note about enums:

an Enum by default has an int under­neath, and as do all inte­gers in C# an enum has a default value of 0 when first cre­ated. So if 0 is not mapped to an enu­mer­a­tion con­stant then your enum will be instan­ti­ated with an invalid valid

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

You are missing the Flags attribute...

Your enum should be declared like this:

[Flags]
public enum ItemTags { Browsable = 2, IsInMenu = 4}

EDIT:
After your update, it looks fine. You should be more precise in what you mean with:

But I don't get the desired result.

The code you showed us looks fine. So either there is a problem elsewhere or the code you really use in your application and the code you showed us here are different.

Upvotes: 1

Gleno
Gleno

Reputation: 16969

You need to use FlagsAttribute, see this MSDN article, and this usage example, and most importantly this stack overflow answer.

Upvotes: 2

Related Questions