Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 298
Dave Avatar asked May 30 '11 14:05

Dave


4 Answers

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.

like image 183
Matías Fidemraizer Avatar answered Oct 22 '22 21:10

Matías Fidemraizer


This is not an optimization.

No, nothing like that exists, and for good reason. It's much less readable and there's absolutely zero benefit to be gained in doing so. Declare them in two separate statements and be done with it.

If you're literally getting paid to reduce the number of lines in your source code, write it like this:

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

(Yes, that's a joke. Mostly.)

like image 22
Cody Gray Avatar answered Oct 22 '22 23:10

Cody Gray


Switching from C/C++, I suppose?

No, can't do that

like image 44
Dyppl Avatar answered Oct 22 '22 22:10

Dyppl


No, that doesnt exists. Nor is it very readable IMHO

like image 39
TJHeuvel Avatar answered Oct 22 '22 22:10

TJHeuvel