Search code examples
c#asp.net-mvc-3enumsenum-flags

What is the internal logic for Enum HasFlag function implementation


Can someone please help me to understand the internal logic of HasFlag method for a enum class? Let me first explain my requirement. I have already created an enum with flag attribute, and then used HasFlag() function to get selected combination from a bit flag value. But here my requirement is different. I have a table in my DB, which is having different enumeration values listed. the structure is like below.

EnumTypeID    EnumVal      EnumID     Description 
===========  ==========   =========  ================
   1           enum1          0         xxxxxxxxx
   1           enum2          1         xxxxxxxxx
   1           enum3          2         xxxxxxxxx
   2           enum4          0         xxxxxxxxx
   2           enum5          1         xxxxxxxxx

Let's say I have another table, which is storing the final flag combination for EnumTypeID 1. So that table column is suppose to save different combination like

0 = Nothing selected
1 = enum1 selected
2 = enum2 selected
3 = enum1 & enum2 selected
4 = enum3 selected
5 = enum1 & enum3 selected
6 = enum2 & enum3 selected
7 = enum1 & enum2 & enum3 selected

=============================================================

Now how can I programmatically(in C# .net4.5) achieve this. I need to first query the first table and get the list of enumeration for a specific EnumTypeID. Now I need to get the value from the second table for the selected flag (let's say the value is 5). Then how I can say that basically enum1 & enum3 is selected through code?


Solution

  • as you can see in the below link the HasFlag returns the result of thisInstance And flag = flag expression

    Enum.HasFlag

    see remarks section

    and if I got your question correctly you need a query like this:

    select * from SecondTable where FlagColumn & 5 = 5