Wouldn't Enum generic constraints be nice?

by timvasil 10/31/2007 11:48:00 AM

I wanted to design a utility class that provided some bit manipulation methods for enums with [Flags].  Ideally I wanted to embed these methods directly in the enum definition like I can do in Java, but no such luck in C#.  So the helper class seemed like the next best thing.

Turns out this is pretty hard to do!  You can't build a class with the constraint where T : Enum, for example.  Bill Rodenbaugh comes close in his enum helper class, Enum<T>. 

But when all is said and done, using the helper class doesn't really improve upon readability, efficiency, or even number of characters typed!

Here's a sample using the helper class:

public bool Enabled
{
   
get { return !Enum<MenuItemAttributes>.Flags.IsFlagSet(_attributes, MenuItemAttributes.Disabled); }
   
set { _attributes = Enum<MenuItemAttributes>.Flags.SetOrClearFlag(_attributes, MenuItemAttributes.Disabled, value); }
}

And the alternative--doing bit manipulations directly:

public bool Enabled
{
   
get { return (_attributes & MenuItemAttributes.Disabled) != MenuItemAttributes.Disabled; }
   
set { if (value) _attributes |= ~MenuItemAttributes.Disabled; else _attributes &= MenuItemAttributes.Disabled; }
}

I'm going to stick to manual bit manipulations!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET Framework

Related posts

Comments

Comments are closed

 

About the author

Tim Vasil Tim Vasil
I'm a software engineer living in Cambridge, MA.

E-mail me Send mail

Search

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent comments