Enum.HasFlag: good or bad?
.NET 4 give us nice elegant way of checking whether [Flags] enums
contain a value.
assuming that we have the following enum:
we can use the bitwise for checking whether instantiation of
the enum contain a value, as shown in the next snippet:
.NET 4 come with elegant syntax which look like the following:
whether it good or bad to use the new syntax we will discover soon,
anyway it is surely not ugly.
What’s the problem with this syntax?
the problem with the syntax is that it is not syntactic sugar (as we might thought).
as elegant and convenient it is, it is hiding reflection operations (GetType()).
using this syntax under intensive iteration you may lead to performance hit.
the following output show the effect of having Enum.HasFlag inside intensive iteration:
the full code for this test can be find at:
basically it compare
Enum.HasFlag is definitely slower than the bitwise comparison, but it is cleaner
and more readable.
therefore I may argue that it is OK to use it unless it is under intensive iteration.
point of interest
the implementation of Enum.HasFlag is: