<p>From time to time I see an enum like the following:</p>

<pre><code>[Flags]
public enum Options 
{
    None    = 0,
    Option1 = 1,
    Option2 = 2,
    Option3 = 4,
    Option4 = 8
}
</code></pre>

<p>I don't understand what exactly the <code>[Flags]</code> attribute does.</p>

<p>Anyone have a good explanation or example they could post?</p>

[{'answer_id': 8455, 'author': 'Jay Mooney', 'author_id': 733, 'author_profile': 'https://Stackoverflow.com/users/733', 'pm_score': 4, 'selected': False, 'text': '<p>Flags allow you to use bitmasking inside your enumeration.  This allows you to combine enumeration values, while retaining which ones are specified.</p>\n\n<pre><code>[Flags]\npublic enum DashboardItemPresentationProperties : long\n{\n    None = 0,\n    HideCollapse = 1,\n    HideDelete = 2,\n    HideEdit = 4,\n    HideOpenInNewWindow = 8,\n    HideResetSource = 16,\n    HideMenu = 32\n}\n</code></pre>\n'}, {'answer_id': 8460, 'author': 'OJ.', 'author_id': 611, 'author_profile': 'https://Stackoverflow.com/users/611', 'pm_score': 6, 'selected': False, 'text': '<p>Please see the following for an example which shows the declaration and potential usage:</p>\n\n<pre><code>namespace Flags\n{\n    class Program\n    {\n        [Flags]\n        public enum MyFlags : short\n        {\n            Foo = 0x1,\n            Bar = 0x2,\n            Baz = 0x4\n        }\n\n        static void Main(string[] args)\n        {\n            MyFlags fooBar = MyFlags.Foo | MyFlags.Bar;\n\n            if ((fooBar &amp; MyFlags.Foo) == MyFlags.Foo)\n            {\n                Console.WriteLine("Item has Foo flag set");\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 8462, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 10, 'selected': False, 'text': "<p>You can also do this</p>\n\n<pre><code>[Flags]\npublic enum MyEnum\n{\n    None   = 0,\n    First  = 1 &lt;&lt; 0,\n    Second = 1 &lt;&lt; 1,\n    Third  = 1 &lt;&lt; 2,\n    Fourth = 1 &lt;&lt; 3\n}\n</code></pre>\n\n<p>I find the bit-shifting easier than typing 4,8,16,32 and so on. It has no impact on your code because it's all done at compile time</p>\n"}, {'answer_id': 8480, 'author': 'andynil', 'author_id': 446, 'author_profile': 'https://Stackoverflow.com/users/446', 'pm_score': 12, 'selected': True, 'text': '<p>The <code>[Flags]</code> attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:</p>\n\n<pre><code>var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;\n</code></pre>\n\n<p>Note that the <code>[Flags]</code> attribute <strong>doesn\'t</strong> enable this by itself - all it does is allow a nice representation by the <code>.ToString()</code> method:</p>\n\n<pre><code>enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }\n[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }\n\n...\n\nvar str1 = (Suits.Spades | Suits.Diamonds).ToString();\n           // "5"\nvar str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();\n           // "Spades, Diamonds"\n</code></pre>\n\n<p>It is also important to note that <code>[Flags]</code> <strong>does not</strong> automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment. </p>\n\n<p>Incorrect declaration:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n    Yellow,  // 0\n    Green,   // 1\n    Red,     // 2\n    Blue     // 3\n}\n</code></pre>\n\n<p>The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.</p>\n\n<p>Here\'s an example of a correct declaration:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n    Yellow = 1,\n    Green = 2,\n    Red = 4,\n    Blue = 8\n}\n</code></pre>\n\n<p>To retrieve the distinct values in your property, one can do this:</p>\n\n<pre><code>if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))\n{\n    // Yellow is allowed...\n}\n</code></pre>\n\n<p>or prior to .NET 4:</p>\n\n<pre><code>if((myProperties.AllowedColors &amp; MyColor.Yellow) == MyColor.Yellow)\n{\n    // Yellow is allowed...\n}\n\nif((myProperties.AllowedColors &amp; MyColor.Green) == MyColor.Green)\n{\n    // Green is allowed...\n}    \n</code></pre>\n\n<p><strong>Under the covers</strong></p>\n\n<p>This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:</p>\n\n<pre><code> Yellow: 00000001\n Green:  00000010\n Red:    00000100\n Blue:   00001000\n</code></pre>\n\n<p>Similarly, after you\'ve set your property <em>AllowedColors</em> to Red, Green and Blue using the binary bitwise OR <code>|</code> operator, <em>AllowedColors</em> looks like this:</p>\n\n<pre><code>myProperties.AllowedColors: 00001110\n</code></pre>\n\n<p>So when you retrieve the value you are actually performing bitwise AND <code>&amp;</code> on the values:</p>\n\n<pre><code>myProperties.AllowedColors: 00001110\n             MyColor.Green: 00000010\n             -----------------------\n                            00000010 // Hey, this is the same as MyColor.Green!\n</code></pre>\n\n<p><strong>The None = 0 value</strong></p>\n\n<p>And regarding the use of <code>0</code> in your enumeration, quoting from MSDN:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n    None = 0,\n    ....\n}\n</code></pre>\n\n<blockquote>\n  <p>Use None as the name of the flag enumerated constant whose value is zero. <strong>You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero.</strong> However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. </p>\n</blockquote>\n\n<p>You can find more info about the flags attribute and its usage at <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="noreferrer">msdn</a> and <a href="http://msdn.microsoft.com/en-us/library/ms229062.aspx" rel="noreferrer">designing flags at msdn</a></p>\n'}, {'answer_id': 8526, 'author': 'David Wengier', 'author_id': 489, 'author_profile': 'https://Stackoverflow.com/users/489', 'pm_score': 4, 'selected': False, 'text': '<p>To add <code>Mode.Write</code>:</p>\n\n<pre><code>Mode = Mode | Mode.Write;\n</code></pre>\n'}, {'answer_id': 8975, 'author': 'steve_c', 'author_id': 769, 'author_profile': 'https://Stackoverflow.com/users/769', 'pm_score': 5, 'selected': False, 'text': '<p>@Nidonocu</p>\n\n<p>To add another flag to an existing set of values, use the OR assignment operator.</p>\n\n<pre><code>Mode = Mode.Read;\n//Add Mode.Write\nMode |= Mode.Write;\nAssert.True(((Mode &amp; Mode.Write) == Mode.Write)\n  &amp;&amp; ((Mode &amp; Mode.Read) == Mode.Read)));\n</code></pre>\n'}, {'answer_id': 9117, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 5, 'selected': False, 'text': '<p>I <a href="https://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint">asked recently</a> about something similar.</p>\n\n<p>If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)</p>\n\n<p>This allows you to do:</p>\n\n<pre><code>[Flags]\npublic enum PossibleOptions : byte\n{\n    None = 0,\n    OptionOne = 1,\n    OptionTwo = 2,\n    OptionThree = 4,\n    OptionFour = 8,\n\n    //combinations can be in the enum too\n    OptionOneAndTwo = OptionOne | OptionTwo,\n    OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree,\n    ...\n}\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree \n\nif( opt.IsSet( PossibleOptions.OptionOne ) ) {\n    //optionOne is one of those set\n}\n</code></pre>\n\n<p>I find this easier to read than the most ways of checking the included flags.</p>\n'}, {'answer_id': 16328309, 'author': 'ruffin', 'author_id': 1028230, 'author_profile': 'https://Stackoverflow.com/users/1028230', 'pm_score': 4, 'selected': False, 'text': '<p>There\'s something overly verbose to me about the <code>if ((x &amp; y) == y)...</code> construct, especially if <code>x</code> AND <code>y</code> are both compound sets of flags and you only want to know if there\'s <strong>any</strong> overlap.</p>\n\n<p>In this case, all you really need to know is <strong>if there\'s a non-zero value[1] after you\'ve bitmasked</strong>.  </p>\n\n<blockquote>\n  <p>[1] See Jaime\'s comment.  If we were authentically <em>bitmasking</em>, we\'d\n  only need to check that the result was positive.  But since <code>enum</code>s\n  can be negative, even, strangely, when combined with <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="noreferrer">the <code>[Flags]</code>\n  attribute</a>,\n  it\'s defensive to code for <code>!= 0</code> rather than <code>&gt; 0</code>.</p>\n</blockquote>\n\n<p>Building off of @andnil\'s setup...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace BitFlagPlay\n{\n    class Program\n    {\n        [Flags]\n        public enum MyColor\n        {\n            Yellow = 0x01,\n            Green = 0x02,\n            Red = 0x04,\n            Blue = 0x08\n        }\n\n        static void Main(string[] args)\n        {\n            var myColor = MyColor.Yellow | MyColor.Blue;\n            var acceptableColors = MyColor.Yellow | MyColor.Red;\n\n            Console.WriteLine((myColor &amp; MyColor.Blue) != 0);     // True\n            Console.WriteLine((myColor &amp; MyColor.Red) != 0);      // False                \n            Console.WriteLine((myColor &amp; acceptableColors) != 0); // True\n            // ... though only Yellow is shared.\n\n            Console.WriteLine((myColor &amp; MyColor.Green) != 0);    // Wait a minute... ;^D\n\n            Console.Read();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 16591032, 'author': 'drzaus', 'author_id': 1037948, 'author_profile': 'https://Stackoverflow.com/users/1037948', 'pm_score': 7, 'selected': False, 'text': '<p>Combining answers <a href="https://stackoverflow.com/a/8462/1037948">https://stackoverflow.com/a/8462/1037948</a> (declaration via bit-shifting) and <a href="https://stackoverflow.com/a/9117/1037948">https://stackoverflow.com/a/9117/1037948</a> (using combinations in declaration) you can bit-shift previous values rather than using numbers.  Not necessarily recommending it, but just pointing out you can.</p>\n\n<p>Rather than:</p>\n\n<pre><code>[Flags]\npublic enum Options : byte\n{\n    None    = 0,\n    One     = 1 &lt;&lt; 0,   // 1\n    Two     = 1 &lt;&lt; 1,   // 2\n    Three   = 1 &lt;&lt; 2,   // 4\n    Four    = 1 &lt;&lt; 3,   // 8\n\n    // combinations\n    OneAndTwo = One | Two,\n    OneTwoAndThree = One | Two | Three,\n}\n</code></pre>\n\n<p>You can declare</p>\n\n<pre><code>[Flags]\npublic enum Options : byte\n{\n    None    = 0,\n    One     = 1 &lt;&lt; 0,       // 1\n    // now that value 1 is available, start shifting from there\n    Two     = One &lt;&lt; 1,     // 2\n    Three   = Two &lt;&lt; 1,     // 4\n    Four    = Three &lt;&lt; 1,   // 8\n\n    // same combinations\n    OneAndTwo = One | Two,\n    OneTwoAndThree = One | Two | Three,\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Confirming with LinqPad:</strong></p>\n\n<pre><code>foreach(var e in Enum.GetValues(typeof(Options))) {\n    string.Format("{0} = {1}", e.ToString(), (byte)e).Dump();\n}\n</code></pre>\n\n<p>Results in:</p>\n\n<pre><code>None = 0\nOne = 1\nTwo = 2\nOneAndTwo = 3\nThree = 4\nOneTwoAndThree = 7\nFour = 8\n</code></pre>\n'}, {'answer_id': 45212972, 'author': 'Thorkil Holm-Jacobsen', 'author_id': 1206487, 'author_profile': 'https://Stackoverflow.com/users/1206487', 'pm_score': 6, 'selected': False, 'text': '<p>In extension to the accepted answer, in C#7 the enum flags can be written using binary literals:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n    None   = 0b0000,\n    Yellow = 0b0001,\n    Green  = 0b0010,\n    Red    = 0b0100,\n    Blue   = 0b1000\n}\n</code></pre>\n\n<p>I think this representation makes it clear how the flags work <em>under the covers</em>.</p>\n'}, {'answer_id': 52944774, 'author': 'Jpsy', 'author_id': 430742, 'author_profile': 'https://Stackoverflow.com/users/430742', 'pm_score': 5, 'selected': False, 'text': '<p>When working with flags I often declare additional None and All items. These are helpful to check whether all flags are set or no flag is set. </p>\n\n<pre><code>[Flags] \nenum SuitsFlags { \n\n    None =     0,\n\n    Spades =   1 &lt;&lt; 0, \n    Clubs =    1 &lt;&lt; 1, \n    Diamonds = 1 &lt;&lt; 2, \n    Hearts =   1 &lt;&lt; 3,\n\n    All =      ~(~0 &lt;&lt; 4)\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Spades | Clubs | Diamonds | Hearts == All  // true\nSpades &amp; Clubs == None  // true\n</code></pre>\n\n<p>&nbsp;<br>\n<strong>Update 2019-10:</strong></p>\n\n<p>Since C# 7.0 you can use binary literals, which are probably more intuitive to read:</p>\n\n<pre><code>[Flags] \nenum SuitsFlags { \n\n    None =     0b0000,\n\n    Spades =   0b0001, \n    Clubs =    0b0010, \n    Diamonds = 0b0100, \n    Hearts =   0b1000,\n\n    All =      0b1111\n\n}\n</code></pre>\n'}, {'answer_id': 59940035, 'author': 'kbvishnu', 'author_id': 438624, 'author_profile': 'https://Stackoverflow.com/users/438624', 'pm_score': 1, 'selected': False, 'text': '<p>Apologies if someone already noticed this scenario. A perfect example of flags we can see in reflection. Yes <a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=netframework-4.8" rel="nofollow noreferrer">Binding Flags ENUM</a>.</p>\n<pre class="lang-cs prettyprint-override"><code>[System.Flags]\n[System.Runtime.InteropServices.ComVisible(true)]\n[System.Serializable]\npublic enum BindingFlags\n</code></pre>\n<p><strong>Usage</strong></p>\n<pre class="lang-cs prettyprint-override"><code>// BindingFlags.InvokeMethod\n// Call a static method.\nType t = typeof (TestClass);\n\nConsole.WriteLine();\nConsole.WriteLine(&quot;Invoking a static method.&quot;);\nConsole.WriteLine(&quot;-------------------------&quot;);\nt.InvokeMember (&quot;SayHello&quot;, BindingFlags.InvokeMethod | BindingFlags.Public | \n    BindingFlags.Static, null, null, new object [] {});\n</code></pre>\n'}, {'answer_id': 64782547, 'author': 'Mukesh Pareek', 'author_id': 4360948, 'author_profile': 'https://Stackoverflow.com/users/4360948', 'pm_score': -1, 'selected': False, 'text': '<ul>\n<li><p>Flags are used when an enumerable value represents a collection of\nenum members.</p>\n</li>\n<li><p>here we use bitwise operators, | and &amp;</p>\n</li>\n<li><p>Example</p>\n<pre><code>             [Flags]\n             public enum Sides { Left=0, Right=1, Top=2, Bottom=3 }\n\n             Sides leftRight = Sides.Left | Sides.Right;\n             Console.WriteLine (leftRight);//Left, Right\n\n             string stringValue = leftRight.ToString();\n             Console.WriteLine (stringValue);//Left, Right\n\n             Sides s = Sides.Left;\n             s |= Sides.Right;\n             Console.WriteLine (s);//Left, Right\n\n             s ^= Sides.Right; // Toggles Sides.Right\n             Console.WriteLine (s); //Left\n</code></pre>\n</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/8447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/580/']