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)?
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:
Perhaps re-define your enum as the following:
The
Enumclass has some handy methods to work with enums – such asIsDefinedto find out if a variable holds a defined value of the enumeration.