New Helper Methods in .NET 4 (or, A Great New Method With a Caveat)
On Twitter yesterday, Brad Abrams mentioned String.IsNullOrWhiteSpace, to awesome new helper to replace compliment String.IsNullOrEmpty. I'm really excited to get to use this, since it seems like it makes more sense in the majority of cases than IsNullOrEmpty.
But that's not the point of this blog post. After Brad made that comment, Josh Einstein replied and asked why Enum.HasFlag wasn't getting any love, and I have to agree, having not heard this mentioned before. Just the other day I was working with a GridView and had to check the rows' RowState, which is a Flags enum. After having to remember the right way to check a flag enum, I thought to myself, "why isn't this part of the framework? I shouldn't have to do bitwise logic to check this..." That's why I get excited learning about this new method in .NET 4.)
However, as I read the MSDN documentation for the method, I realized that it has the same pitfall that I ran into when doing it myself. Basically, the right way to check whether a flag is set is to use the bitwise AND operator (&) on the value and the desired flag, and then compare that to the desired flag, i.e. (value & DataControlRowState.Alternate) == DataControlRowState.Alternate will check if value contains the Alternate flag. When Enum.FlagValue is zero (i.e. DataControlRowState.Normal), then this algorithm always returns true, regardless of the value you are checking, which is rarely the result that you want.
So, the result is that Enum.HasFlag is a great addition to the framework (so long as people know about it, so that it gets used in place of the old manual method), however, you have to know what you're doing, and specifically you will need to do something different when you're checking against an enum value that is zero (the best check in that case is probably just equality, i.e. value == DataControlRowState.Normal).