Do I need to manually list FlagsAttribute flags manually?

To allow various formatting options for the method displaying the news story, I created an enumeration that can be passed to specify how it will be displayed.

[Flags] private enum NewsStyle { Thumbnail = 0, Date = 1, Text = 2, Link = 4, All = 8 } string FormatNews( DataRow news, NewsStyle style ) { StringBuilder HTML = new StringBuilder(); // Should the link be shown if ( ((newsStyle & NewsStyle.All) == NewsStyle.All || (newsStyle & NewsStyle.Link) == NewsStyle.Link)) { HTML.AppendFormat("<a style=\"text-decoration:none; color: rgb(66, 110, 171);\" href=\"ViewStory.aspx?nsid={0}\">", UrlEncode(newsStory["NewsStoryID"].ToString())); } // Etc etc... } // So to call the method... Response.Write( FormatNews( news, NewsStyle.Date | NewsStyle.Text ) ); 

The problem is that I can make the code work if I manually specify the values ​​in the enumeration, otherwise the operation of checking the bitwise enumeration will not work correctly.

I have always followed the let.net rule to handle assignment of values ​​to enumerations - is this an exceptional exception?

+4
source share
2 answers

Yes, this is a real exception. By default, enumerations are assigned values ​​from 0 to, each one higher than the previous value, regardless of any FlagsAttribute s. (Of course, more complex rules when specifying some values ​​manually - see MSDN docs )

Although it makes some sense that the flag enumeration automatically gets values ​​in powers of two, I see reasons why it is probably better not to do this:

It is perfectly reasonable to have an enumeration like this:

 [Flags] enum Foo { None, Bar, Baz, BarAndBaz } 

This, of course, requires that the values ​​be 0, 1, 2, and 3.

It would be pretty counter-intuitive for the presence of a simple attribute to change the whole meaning of a piece of C # code. Consider my Foo example. Should deleting the Flags attribute allow breaking the code by silently changing the counter values?

+8
source

Yes, you must specify the values ​​in Enum in order to get the correct values ​​for the added flags (in order to be able to combine the two enum flags and not have this value conflict with the specified other flag). You do not need to specify values ​​to compile it, but the result is most likely not the one you are looking for.

0
source

All Articles