Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an instance of an C# Enum with no 0 value

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.

like image 483
Lieven Cardoen Avatar asked Jan 26 '11 12:01

Lieven Cardoen


1 Answers

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.

like image 194
Timwi Avatar answered Oct 04 '22 02:10

Timwi