Friday, February 23, 2007

Defining values in enums

I got caught out earlier with something not working as I expected. It may well be documented behaviour somewhere, but I've not been able to find anything specifically mentioning it following a brief search, so I thought I'd document it.

In an attempt to follow the guidelines for declaring an enum, specifically, placing the values in alphabetical order and providing a default "zero value", I came up with the following:


public enum Decision {
  Accept,
  Error,
  Reject,
  Unknown = 0
}



Unfortunately this leads to the following values being assigned:
Accept = 0
Error = 1
Reject = 2
Unknown = 0

and thus Accept and Unknown become one and the same.

Make sure that any that are declared with a value go above any that aren't!