Jul 23
You can count the number of constants defined in a C# enumeration with the static Enum.GetNames method. This returns an Array containing the names of the constants defined in the enumeration. You can then check the Array’s Length property.
For example, to get the number of constants defined in the ContentAlignment enumeration:
int count = Enum.GetValues( typeof( ContentAlignment ) ).Length;
Note that you can also use the Enum.GetValues method to count the items in an enumeration, however GetNames is 10X faster than GetValues! Perhaps this performance difference is the result of boxing and unboxing of integer values in the Array for Enum.GetValues? Comment if you know why.
Enums are very cool but a little annoying to extract information from. I use Enum.GetNames() to populate ComboBoxes. If I want the value based on the Name, I use Enum.Parse to get an Enum variable and then cast it back into an int. You can see this here http://www.developingfor.net/net-20/finding-an-enum-value-based-on-its-text.html
I can’t say though why GetValues would be any slower than GetNames. It may be beause GetValues returns an Array object, while GetNames returns an array of strings. There may be some subtle difference in that distinction that is causing the slow down.
Nice Blog, but I can’t find a Feed anywhere…
Re: Nice Blog, but I can’t find a Feed anywhere…
Thanks!
There is a “Subscribe via RSS” link in the middle column. You can also go here:
http://feeds.feedburner.com/Devtopics
Thanks for the link Timm, I did subscribe. Unfortunately I see no “middle” column. In fact, I only see the main blog postings column using FireFox. I opend your site in IE and I can see everything. Just thought you’d like to know… from the look sof it, FireFox users are missing a lot on your blog!
D’oh! Thanks for the heads-up.
The irony here is that one of the great promises of the Web is its ability to render the platform irrelevant so that it doesn’t really matter what operating system you are using. While that is mostly true, the dependency has shifted to the browser. And so now developers (and even novice bloggers) must concern themselves with all the subtle intracies and differences between browsers. Is that truly progress, or simply shifting papers on the desk? Sounds like a good subject for a future article. 😉