I am using Enum flags in my application. The Enum can have around 50+ values, so values go up to 2^50. I was just wondering, can I use Math.Pow(2, variable)
to calculate these?
When I try to do that I get a constant value compile-time error. Is there another way, other than calculating these powers of 2 manually and putting it in?
Here's what I am doing:
[Flags] internal enum RiskStates : long { None = 0, AL = Convert.ToInt64(Math.Pow(2,0)), AK = 2, AZ = 4, AR = 8, CA = 16, CO = 32, CT = 64, DC = 128, DE = 256, FL = 512, GA = 1024, HI = 2048, ID = 4096, IL = 8192, IN = 16384, IA = 32768, KS = 65536, KY = 131072, LA = 262144, ME = 524288, MD = 1048576, MA = 2097152, MI = 4194304 }
Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.
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.
In general, "Flag" is just another term for a true/false condition. It may have more specific meanings in more specific contexts. For instance, a CPU may keep "arithmetic flags", each one indicating a true/false condition resulting from the previous arithmetic operation.
When I try to do that I get a constant value compile-time error.
You'd actually be okay if you used the L
suffix to force it to be a long
literal - but it's still not ideal to have to specify them all manually. (It's not "obviously correct" when reading the code.)
You can't use Math.Pow
as the expression has to be a compile-time constant - but you can use bit-shifting:
None = 0, AL = 1L << 0, AK = 1L << 1, AZ = 1L << 2
etc. I'd argue that's more readable anyway :)
If you change to using non-decimal notations where the powers of 2 are more regular then you will no longer need to generate them automatically, e.g.:
// octal AL = 0001L, AK = 0002L, AZ = 0004L, AR = 0010L, CA = 0020L, CO = 0040L, CT = 0100L, ... // hexadecimal AL = 0x001L, AK = 0x002L, AZ = 0x004L, AR = 0x008L, CA = 0x010L, CO = 0x020L, CT = 0x040L, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With