In C #, is there a way to define an enumeration and an instance of this enumeration at the same time?

Looking for code optimization in C # that allows me to both define an enumeration and create a variable of this enumeration type at the same time:

Before:

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

After (not working):

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

Is there anything similar?

+6
source share
5 answers

There is no support for this in C #, but maybe you can get around this and do something “next to” the listing using tuples or anonymous types if you only need to switch some state and you don't need to do any or special operations with it.

For example, using tuples, you can do this:

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

UPDATE :

C # 7 introduced syntax 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 is not an actual enumeration, and you don’t have the sugar that the Enum type provides you, but you can still use binary operators such as OR, AND or legend, like any other actual enumeration.

+8
source

This is not an optimization.

No, nothing of the kind exists and not in vain. This is much less readable, and it gives an absolutely zero advantage. Declare them in two separate statements and make with it.

If you are literally paid to reduce the number of lines in the source code, write it as follows:

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

(Yes, this is a joke. Mostly.)

+6
source

Switching from C / C ++, I suppose?

No, can't do it.

+2
source

No, this does not exist. And this is not very readable IMHO

+1
source

No, in C #, the declaration or type and use of this type to declare variables are separate.

In C / C ++, it is usually declared and uses the type directly, for example, with the struct keyword. In C # they are separated.

Note that in C # you don't need a semicolon after the enum declaration (or class or struct ):

 enum State { State1, State2, State3 } 

This is still allowed, although it seems to be slightly more compatible with the C / C ++ syntax.

0
source

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


All Articles