4

I've made the following test code:

public enum Test
{
    One = 1,
    Two = 2
}
public class User
{
    public Test Flag { get; set; }
}

Which I use like this:

var user = new User();
var value = typeof(Test).GetField(user.Flag.ToString());

Value will be null since it seems like User.Flag is initialized with 0. Why is that? 0 is not a valid value for my enum. Shouldn't it be initialized with the first valid value (1)?

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • See this answer: http://stackoverflow.com/q/1165414/25727 – Jan Nov 24 '11 at 14:59
  • possible duplicate of [Question on Initial Value of an Enum (C#)](http://stackoverflow.com/questions/1165402/question-on-initial-value-of-an-enum-c) – jgauffin Nov 24 '11 at 15:00
  • @Jan: Thanks. Didn't see that one. Closing my own question as a dup – jgauffin Nov 24 '11 at 15:00
  • Not quite the duplicate, as the other question does not define values on the enum (so the first item _would_ have a value of `0`). The answers to that one do apply though. – Oded Nov 24 '11 at 15:03

4 Answers4

4

Enums are backed by integral types and behave like them (mostly).

Unfortunately, that means that you can assign any value that is valid on the underlying type to an enum - there is no checking.

In the case of default initialization, that would be the default value of the underlying type, which for integral types is 0.

You can do this as well and it will compile and run:

var value = (Test)43;

Perhaps re-define your enum as the following:

public enum Test
{
    None = 0,
    One = 1,
    Two = 2
}

The Enum class has some handy methods to work with enums - such as IsDefined to find out if a variable holds a defined value of the enumeration.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

It's initialised with the default of the underlying type, which is int and default(int) is 0.

George Duckett
  • 31,770
  • 9
  • 95
  • 162
1

Underlying type of the Enum is int type by default, and default value obviously is 0 (you can specify custom underlying type but only primitive numeric like enum CustomEnum : byte)

1.10 Enums, C# Specification:

Each enum type has a corresponding integral type called the underlying type of the enum type. An enum type that does not explicitly declare an underlying type has an underlying type of int. An enum type’s storage format and range of possible values are determined by its underlying type. The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type.

sll
  • 61,540
  • 22
  • 104
  • 156
-1

GetField takes the name of the property name, and you are passing the enum value of user.Flag

You should write

var value = (Test) typeof(Test).GetField("Flag").GetValue(user);
Abdul Munim
  • 18,869
  • 8
  • 52
  • 61