开发者

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

开发者 https://www.devze.com 2023-03-09 13:13 出处:网络
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:

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 sta开发者_StackOverflow社区te = State.State1;

After (doesn't work):

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

Does anything like that exist?


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.


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.)


Switching from C/C++, I suppose?

No, can't do that


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


No, in C# the declaration or a type and using that type to declare variables are separate.

In C/C++ it's common to declare and use a type directly, for example with the struct keyword. In C# they are separate.

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

enum State { State1, State2, State3 }

It's still allowed though, presumably to be a little more compatible with C/C++ syntax.

0

精彩评论

暂无评论...
验证码 换一张
取 消