Enum types, FlagAttribute & Zero value
Posted
by nmgomes
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by nmgomes
Published on Thu, 05 Jul 2012 02:17:31 GMT
Indexed on
2012/07/05
3:16 UTC
Read the original article
Hit count: 289
We all know about Enums types and use them every single day. What is not that often used is to decorate the Enum type with the FlagsAttribute.
When an Enum type has the FlagsAttribute we can assign multiple values to it and thus combine multiple information into a single enum.
The enum values should be a power of two so that a bit set is achieved.
Here is a typical Enum type:
public enum OperationMode { /// <summary> /// No operation mode /// </summary> None = 0, /// <summary> /// Standard operation mode /// </summary> Standard = 1, /// <summary> /// Accept bubble requests mode /// </summary> Parent = 2 }
In such scenario no values combination are possible. In the following scenario a default operation mode exists and combination is used:
[Flags] public enum OperationMode { /// <summary> /// Asynchronous operation mode /// </summary> Async = 0, /// <summary> /// Synchronous operation mode /// </summary> Sync = 1, /// <summary> /// Accept bubble requests mode /// </summary> Parent = 2 }
Now, it’s possible to do statements like:
[DefaultValue(OperationMode.Async)] [TypeConverter(typeof(EnumConverter))] public OperationMode Mode { get; set; } /// <summary> /// Gets a value indicating whether this instance supports request from childrens. /// </summary> public bool IsParent { get { return (this.Mode & OperationMode.Parent) == OperationMode.Parent; } }
or
switch (this.Mode) { case OperationMode.Sync | OperationMode.Parent: Console.WriteLine("Sync,Parent"); break;
[…]
But there is something that you should never forget: Zero is the absorber element for the bitwise AND operation.
So, checking for OperationMode.Async (the Zero value) mode just like the OperationMode.Parent mode makes no sense since it will always be true:
(this.Mode & 0x0) == 0x0
Instead, inverse logic should be used: OperationMode.Async = !OperationMode.Sync
public bool IsAsync { get { return (this.Mode & ContentManagerOperationMode.Sync) != ContentManagerOperationMode.Sync; } }
or
public bool IsAsync { get { return (int)this.Mode == 0; } }
Final Note:
Benefits
Allow multiple values combination
The above samples snippets were taken from an ASP.NET control and enabled the following markup usage:
<my:Control runat="server" Mode="Sync,Parent">
Drawback
Zero value is the absorber element for the bitwise AND operation
Be very carefully when evaluating the Zero value, either evaluate the enum value as an integer or use inverse logic.
© ASP.net Weblogs or respective owner