In C#, is there way to define an enum and an instance of that enum at the same time?

Dave picture Dave · May 30, 2011 · Viewed 10.7k times · Source

Looking for a code optimization in c# that allows me to both define an enum and create a variable of that enum's type simultaniously:

Before:

    enum State {State1, State2, State3};
    State state = State.State1;

After (doesn't work):

    enum State {State1, State2, State3} state;
    state = State.State1;

Does anything like that exist?

Answer

Matías Fidemraizer picture Matías Fidemraizer · May 30, 2011

There's no support for that in C#, but maybe you can workaround this and do something "near" to an enum by using tuples or anonymous types if you only need to switch some state and you don't need to do any special operations with it.

For example, using tuples, you can do this:

var someFakeEnum = Tuple.Create(0, 1);

UPDATE:

C# 7 has introduced syntactic tuples:

var someFakeEnum = (State1: 0, State2: 1);

Or with anonymous types:

var someFakeEnum = new { State1 = 0, State2 = 1 };

And, after that, you can do something like:

int state = 0;

// If you're using tuples...
if(some condition)
{
    state = someFakeEnum.Item2;
}

// ...or if you're using anonymous types or C# >= 7 tuples...
if(some condition) 
{
    state = someFakeEnum.State2;
}

Obviously this isn't an actual enumeration and you don't have the sugar that Enum type provides for you, but you can still use binary operators like OR, AND or conditionals like any other actual enumeration.