Dan Byström’s Bwain

Blog without an interesting name

Enums and Me, part zero

Posted by Dan Byström on April 17, 2007

enum Why

I have tried to make friendship with .NET Enums for years now, with varying result. My first mishap with them was that I desperately wanted to treat all enum values in the same manner by passing them “by ref” to a function (or I would have been happy with treating them just as integers, as could be done in VB6).

For example, I would have liked to be able to write this:

public void sampleFunction( ref Enum x )

Why why = Why.Not;
sampleFunction( ref why );  // illegal -- won't compile

If you wonder, my sampleFunction is part of a serialization scheme and when the enum is stored in XML I just want to treat it as an integer.

What I currently must do is:

public int sampleFunction( int x )

Why why = Why.Not;
why = (Why)sampleFunction( (int)why );

This is so ugly that it makes me wanna puke. If you can find a better way – please let me know! (Maybe I could use pointers, but that would require me to compile with /unsafe – and that is a road I don’t wanna travel again.)

There is another case when it would have been preferable to have an “enum base class” and that’s when you declare generic classes:

class myGenericClass<T> where T : enum  // no can do

This won’t work either and after googling around a little I know for a fact that I’m not the only one who misses this. The closest we can get seems to be:

class myGenericClass<T> where T : struct, ICompareable

Another thing that has also troubled me is how to map enums to the UI (most notably ComboBoxes). But lately I have arrived at a solution that’s really promising. Not perfect yet but promising. That will be my next post. Stay tuned.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: