Wednesday, January 10, 2007

Caracteristicts of enums

Some time ago I had to map some enums to and from a database. The database would store the integer value and I would cast the enum to and from the database. Suddenly I got unsuspected results even though I had unit testet the functionality with all valid values of the enum. I realized the enum contained an integer value not maped in the enum. No runtime exception was thrown.

I was a bit puzzled by this and I more or less considered this to be some sort of bug in the .Net framework
This is not a bug, and although I sometimes would like it to behave differently, it does give enums a new use.

Consider the following:

Accesories{
  SpareTire = 1,
  ElectricWindows=2,
  Heater=4,
  AirCon=8,

  Standard= SpareTire,
  Family = Standard | ElectricWindows | Heater,
  Luxury = Family | AirCon
}

As shown above it is posible to define your vehicle just by adding the single components. I think MS calls it flags, and the keys issue is that your primitive enum values must map to different bits.
(var & Accesories.Family) == Accesories.Family
will determine whether the level is at least Family. You can use other binary operators to anlyse the value of your enums.

I have succesfully collected data by just adding the simple values together and in the end just validated that it was actually a valid enum value. the validation and decission of the application is build into the structure of the enum instead of written in code.

In the example it is possible to add all primitive values together, but it is also very usefull when you have to select one or the other. Male or female for instance.

I'm looking very much forward to using kanaugh maps together with my enums :D

No comments:

Post a Comment