Enums, Flags and C# -- Oh my!
New Code! An updated blog post on this topic can be found here!
I'm not sure about everyone else, but I just love Enumerated types. Whats more, I love the Flags Attribute when you combine them together. This post explores how you can use these two things along with Extension Methods to make your code more compact and easier to understand.
If you've never used this combination before, then you're missing out. Consider the following code...
Okay, so that's no big deal even though it may be quite a few extra lines of code. It would be nice to be able to combine all of those permissions into a single value. That's where an Enumerated Type with a FlagAttribute comes in.
Excellent.... so now what?
So now whats great about this is now we can assign multiple values onto the same property. Not only that, but we can also check for existing values with a (strange) comparison.
Now shorter and easier to read -- sorta. See that really odd comparison? That's what you need to write each time you want to check for a value. It's not that bad, but it isn't really something I'd like to type very often. You could write a separate function to do these comparisons for you, but we can do even better than that.
Taking Advantage Of Extension Methods
Since an Enumerated type isn't really a class you can't extend methods onto them. However, you can extend methods onto the class System.Enum. Methods added to this class will appear in the methods for all of your enumerated types!.
Here is an example method...
Now, this code does make an assumption that it can cast your Enumerated Type to an integer. You could do some type checking before you do the comparisons, but for the sake of this example, we're going to keep this short.
So just how do you use this extension?
Now that is much easier to read! Even better, you'll notice despite the fact this has a Generic parameter, we don't have to provide the type at the start since the method can infer it from the parameter (implicitly typed parameters -- sweeeeet!)
And don't forget, System.Enum isn't the only class you can do this with, there are other classes (like System.Array for example) that you can add your own extension methods to for surprising results!
Below is the full source code for the EnumerationExtensions class. If you have any improvements, please let me know!
June 13, 2009
Enums, Flags and C# -- Oh my!
Post titled "Enums, Flags and C# -- Oh my! (bad pun...)"