Enums and no field with a value of '0'

I made the following test code:

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

What I use like this:

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

The value will be null , as it appears that User.Flag initialized to 0 . Why is this? 0 not a valid value for my enumeration. Shouldn't it be initialized with the first valid value ( 1 )?

+4
source share
4 answers

Reserves are supported by integral types and behave like them (mostly).

Unfortunately, this means that you can assign any value that is valid for the base type to an enumeration - the check is not performed.

In the case of default initialization, this will be the default value for the base type, which is 0 for integral types.

You can also do this and compile and run:

 var value = (Test)43; 

Perhaps redefine your listing as follows:

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

The Enum class has several convenient methods for working with enumerations - for example, IsDefined , to find out if a variable contains a specific enumeration value.

+2
source

It is initialized by default to the base type, which is int and default(int) 0 .

+2
source

By default, the Enum type has an int type by default, and the default value is 0 (you can specify a custom base type, but only a primitive number, for example enum CustomEnum : byte )

1.10 Enumerations, C # Specification:

Each type of enumeration has a corresponding integral type called the base type of the enumeration type. An enumeration type that does not explicitly declare a base type has an int base type. Enumeration types The storage format and the range of possible values ​​are determined by its base type. A set of values ​​that an enumeration type can use, not limited to its enumeration members. In particular, any value of a base enumeration type can be transferred to an enumeration type and is an excellent valid value for this enumeration type.

+1
source

GetField takes the name of the property name , and you pass the value of the user.Flag

You have to write

 var value = (Test) typeof(Test).GetField("Flag").GetValue(user); 
-1
source

Source: https://habr.com/ru/post/1382909/


All Articles