Choosing the default value of an Enum type without having to change values


In C#, is it possible to decorate an Enum type with an attribute or do something else to specify what the default value should be, without having the change the values? The numbers required might be set in stone for whatever reason, and it'd be handy to still have control over the default.

enum Orientation
    None = -1,
    North = 0,
    East = 1,
    South = 2,
    West = 3

Orientation o; // Is 'North' by default.
5/20/2010 10:38:54 AM

Accepted Answer

The default for an enum (in fact, any value type) is 0 -- even if that is not a valid value for that enum. It cannot be changed.

3/20/2014 9:35:26 AM

The default value of any enum is zero. So if you want to set one enumerator to be the default value, then set that one to zero and all other enumerators to non-zero (the first enumerator to have the value zero will be the default value for that enum if there are several enumerators with the value zero).

enum Orientation
    None = 0, //default value since it has the value '0'
    North = 1,
    East = 2,
    South = 3,
    West = 4

Orientation o; // initialized to 'None'

If your enumerators don't need explicit values, then just make sure the first enumerator is the one you want to be the default enumerator since "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1." (C# reference)

enum Orientation
    None, //default value since it is the first enumerator

Orientation o; // initialized to 'None'

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow