I need to create an instance of an Enum class that hasn't got a 0 value. With a 0 value, next 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 out DUMMY, Creating the instance doesn't work anymore.
I need to create an instance of an Enum class that hasn't got a 0 value.
Assuming an enum like this:
public enum ScheduleStateEnum
{
Draft = 1,
Published = 2,
Archived = 3
}
you can create an instance like this:
ScheduleStateEnum myState = 0;
If you cannot declare a variable of the type 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 give you an instance that actually has the integer value 0
, even if the enum doesn’t declare one. If you want it to default to one of the values you have actually declared, 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 enums that have no values at all defined. Use FirstOrDefault
and check for null
if you want to prevent this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With