Workaround of MS Code Analysis rule CA1008: Enums should have zero value

.net, c#, enums

Solution

The default value for `AlarmType` will be 0. E.g. after this line of code

AlaramType alarmType;

the value of `alarmType` is 0. However, as there is no corresponding enum value it now has an invalid value. That is the reason for the warning and your statement

I don't want to add this because that will (1) violate the definition of AlarmType (AlarmType can't be None) and (2) an extra checking will be necessary to exclude None option when enumerating enum values to present to user.

is not quite true. In fact all instances of `AlarmType` will have the value 0 until they are assigned and if you want to code defensively you will have to verify that `AlarmType` has a valid value. Not defining a name for the value 0 does not in any way protect you from cases where `AlarmType` variables are 0 because they were not initialized.

I would suggest that you define a 0 enum value and call it `Invalid` or `None` or something that describes that the enum variable is not initialized yet.

Or, if you do not want to do that you can suppress the warning using an attribute.

Problem

I'm working on a .NET 4.0/C# project. I've enabled few basic code analysis rules for my project. I'm hit by CA1008. I fully understand why CA1008 is necessary. The software I'm working on communicates with other devices. Those devices are configurable. The configuration is stored in internal EEPROM. One of the configuration is `AlarmType`, in EEPROM which can have a value of 1 to 11. I've defined the alarm type as follows: ``` public enum AlarmType { Type1 = 1, Type2 = 2, Type3 = 3, // ... Type10 = 10, Type11 = 11 } ``` When configuring the devices, I'm allowing the user to select one of the alarm types by fetching alarm values using `Enum.GetValues()`. When inspecting the value in EEPROM, the requirement is like if the value is from 1 to 11, then show the name of the alarm, otherwise consider it `Type1`. Visual Studio 2010 throws a warning stating that `AlarmType` should have a value equals to zero. I don't want to add this because that will (1) violate the definition of `AlarmType` (`AlarmType` can't be `None`) and (2) an extra checking will be necessary to exclude `None` option when enumerating enum values to present to user. Instead of suppressing CA1008, what can I do as a workaround? Have I done something wrong in my design?

Original source