Create C # Enum instance without value 0

I need to create an instance of the Enum class that does not have a value of 0. With a value of 0, the following code works fine:

ObjectFactory.CreateInstance("Edu3.DTOModel.Schedule.ScheduleStateEnum"); 

Enum:

 namespace Edu3.DTOModel.Schedule { public enum ScheduleStateEnum { DUMMY = 0, Draft = 1, Published = 2, Archived = 3 } } 

If I comment on DUMMY, instantiating no longer works.

+4
source share
4 answers

I need to create an instance of the Enum class that does not matter 0.

Assuming an enumeration as follows:

 public enum ScheduleStateEnum { Draft = 1, Published = 2, Archived = 3 } 

you can create an instance like this:

 ScheduleStateEnum myState = 0; 

If you cannot declare a type variable and you need to access the type as a string (as in your example), use Activator.CreateInstance :

 var myState = Activator.CreateInstance(Type.GetType( "Edu3.DTOModel.Schedule.ScheduleStateEnum")); 

Of course, both of these options will provide you with an instance that actually has an integer value of 0 , even if the enumeration does not declare it. If you want it to be one of the values ​​you actually declared by default, you need to use Reflection to find it, for example:

 var myState = Type.GetType("Edu3.DTOModel.Schedule.ScheduleStateEnum") .GetFields(BindingFlags.Static | BindingFlags.Public) .First() .GetValue(null); 

This will crash for listings that have no meaning at all. Use FirstOrDefault and check for null if you want to prevent this.

+6
source

This is a problem with your ObjectFactory class, because

Activator.CreateInstance(typeof(Edu3.DTOModel.Schedule.ScheduleStateEnum))

works fine and creates int 0.

+5
source

This is actually impossible. Enum - to define a value field, so it needs to initialize it with a numerical value of 0.

+2
source

It is best to provide a null enumeration element - see http://msdn.microsoft.com/en-us/library/ms182149%28VS.80%29.aspx . Is there a reason you don't need an element with a null value like None?

+1
source

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


All Articles