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!

Tags:

.NET Framework

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Search

Calendar

«  May 2013  »
SuMoTuWeThFrSa
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Recent posts

Recent comments

Archive