Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the default enum value is 0 and not the minimum one?

Tags:

c#

enums

What's the point of having '0' as a default value for enum in C#? If I declare enumeration that starts with a different number:

enum Color
{
   Blue = 1,
   Green,
   Red,
}

then var color = default(Color) - will return me '0'. I expected to see the minimum value instead. This behavior may cause problems if each member of the enumeration corresponds to some specific number and '0' is not a valid value.

like image 810
username Avatar asked May 24 '12 17:05

username


2 Answers

Default value for all value types (including enum) is bitwise 0. As result it means that 0 is always possible value for enum even if it is not explicitly defined.

Here is the specification: Default values table

EDIT: for more details check MSDN for enumeration types - enum

enum is type which is special in a way the it sort-of derives from other value type (which normally not possible), but behaves as value type of its backing type. An enum can use only some integral values as backing type.

Note: as @archil points out enum value may contain any value of backing type, irrespective of list of constants enumerated in enum itself. For enums marked with "FlagsAttribute" this behavior is normally expected, but for normal enums it may not be intuitive.

like image 171
Alexei Levenkov Avatar answered Sep 21 '22 10:09

Alexei Levenkov


We can only conjecture about why an aspect of the .NET framework was designed a certain way. For the most straightforward explanation, I'd like to highlight this remark from the MSDN documentation:

An enumeration is a set of named constants whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used.

Note that a .NET enumeration is essentially an extension of an integral type. The default value for integral types is 0, so it's reasonable (if somewhat inconvenient in the cases you've illustrated) for enumerations to inherit that behaviour.

like image 22
Dan J Avatar answered Sep 20 '22 10:09

Dan J