Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any trick to defining an enum as flags/powers of 2 without eventually needing a calculator?

Tags:

c#

enums

I know I can multiply but being the lazy programming I am I do not want to.

Has anyone devised some sorcery to auto number the enums as powers of two?

Here's the example I have just to make it concrete:

[Flags] private enum Targets : uint {     None = 0,     Campaigns = 1,     CampaignGroups = 2,     Advertisers = 4,     AdvertiserGroups = 8,     AffiliateGroups = 16,     Affiliates = 32,     Creatives = 64,     DetailedLeads = 128,     DetailedSales = 256,     ProgramLeads = 512,     CreativeDeployments = 1024,     CampaignCategories = 2048,     Payouts = 4096,     All = uint.MaxValue } 
like image 963
Aaron Anodide Avatar asked May 11 '12 21:05

Aaron Anodide


People also ask

What are the first 4 numeric values of an enum used to store flags?

We use the values 0, 1, 2, 4 to indicate the underlying bits for each value—we should double each value to avoid conflicts. Operators We use bitwise operators, like OR and AND, with enum flags.

What is the role of Flag attribute in enums?

The [Flag] attribute is used when Enum represents a collection of multiple possible values rather than a single value. All the possible combination of values will come. The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value.

Can you override an enum C#?

You cannot override enums, and C# does not support return type covariance. You're going to have to find some other way; this is not possible.

Should enums be numbers?

Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


1 Answers

Write the values as shifted bits and let the compiler do the math:

[Flags] private enum Targets : uint {     None                = 0,     Campaigns           = 1,     CampaignGroups      = 2 << 0,     Advertisers         = 2 << 1,     AdvertiserGroups    = 2 << 2,     AffiliateGroups     = 2 << 3,     Affiliates          = 2 << 4,     Creatives           = 2 << 5,     DetailedLeads       = 2 << 6,     DetailedSales       = 2 << 7,     ProgramLeads        = 2 << 8,     CreativeDeployments = 2 << 9,     CampaignCategories  = 2 << 10,     Payouts             = 2 << 11,     // etc. } 

James's suggestion is a good one, too. In fact I like this way even better. You could also write it like this:

[Flags] private enum Targets : uint {     None                = 0,     Campaigns           = 1 << 0,     CampaignGroups      = 1 << 1,     Advertisers         = 1 << 2,     AdvertiserGroups    = 1 << 3,     AffiliateGroups     = 1 << 4,     // etc. } 
like image 112
Cody Gray Avatar answered Oct 22 '22 07:10

Cody Gray