4

Anyone knows the default value for enums using the default keywords as in:

MyEnum myEnum = default(MyEnum);

Would it be the first item?

Joan Venge
  • 315,713
  • 212
  • 479
  • 689

4 Answers4

5

It is the value produced by (myEnum)0. For example:

enum myEnum
{
  foo = 100
  bar = 0,
  quux = 1
}

Then default(myEnum) would be myEnum.bar or the first member of the enum with value 0 if there is more than one member with value 0.

The value is 0 if no member of the enum is assigned (explicitly or implicitly) the value 0.

Richard Cook
  • 32,523
  • 5
  • 46
  • 71
  • Thanks, but what if there is no 0 defined? But they were 100, 99 and 1? – Joan Venge Sep 22 '10 at 22:48
  • Then it is 0. I updated my answer accordingly. See related thread: http://stackoverflow.com/questions/529929/choosing-the-default-value-of-an-enum-type-without-having-to-change-values – Richard Cook Sep 22 '10 at 22:49
  • 3
    If there's no 0 defined, the value is still 0. Remember than an enum is really just a thin typesafe wrapper around an integral type, giving you the ability to reference integral values by name. – Jim Mischel Sep 22 '10 at 22:51
  • Thanks, so if there is no enum 0, you mean the value assigned really be 0 as in int (0)? – Joan Venge Sep 22 '10 at 22:52
  • @Jim: got it now from your comment. – Joan Venge Sep 22 '10 at 22:53
2

It's a bit hard to understand your question, but the default value for an enum is zero, which may or may not be a valid value for the enumeration.

If you want default(MyEnum) to be the first value, you'd need to define your enumeration like this:

public enum MyEnum
{
   First = 0,
   Second,
   Third
}
Bennor McCarthy
  • 11,415
  • 1
  • 49
  • 51
2

The expression default(T) is the equivalent of saying (T)0 for a generic parameter or concrete type which is an enum. This is true whether or not the enum defines an entry that has the numeric value 0.

enum E1 {
  V1 = 1;
  V2 = 2;
}

...

E1 local = default(E1);
switch (local) {
  case E1.V1:
  case E1.V2:
    // Doesn't get hit
    break;
  default:
    // Oops
    break;
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

slapped this into vs2k10.....

with:

 enum myEnum
 {
  a = 1,
  b = 2,
  c = 100
 };



 myEnum  z = default(en);

produces: z == 0 which may or may not be a valid value of your enum (in this case, its not)

thus sayeth visual studio 2k10

Muad'Dib
  • 28,542
  • 5
  • 55
  • 68